使用springboot自带的redisTemplate操作缓存 - Go语言中文社区

使用springboot自带的redisTemplate操作缓存


1.先在pom中引入maven依赖,重点是spring-boot-starter-data-redis

<!--redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
<!--jackson-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
        </dependency>

2.配置redis连接参数

redis:
    host: 127.0.0.1
    port: 6379
    timeout: 10s
    lettuce:
      pool:
        min-idle: 0
        max-idle: 8
        max-active: 8
        max-wait: -1ms

3.配置redisTemplate的相关信息,虽然springboot提供了自动化的配置,但是为了使用我们还是需要自定义一下redisTemplate

定义redisTemplate的配置类RedisTemplateConfig:

package cn.jorian.jorianframework.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.GenericToStringSerializer;

/**
 * redis配置<br>
 * 集群下启动session共享,需打开@EnableRedisHttpSession<br>
 * 单机下不需要
 *
 * @author jorian
 *
 *  2019年3月10日
 */
//@EnableRedisHttpSession
@Configuration
public class RedisTemplateConfig {

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Bean("redisTemplate")
	public RedisTemplate redisTemplate(@Lazy RedisConnectionFactory connectionFactory) {
		RedisTemplate redis = new RedisTemplate();
		GenericToStringSerializer<String> keySerializer = new GenericToStringSerializer<String>(String.class);
		//key序列化方式
		redis.setKeySerializer(keySerializer);
		//哈希key序列化方式
		redis.setHashKeySerializer(keySerializer);

		GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
		//值序列化方式
		redis.setValueSerializer(valueSerializer);
		//哈希值序列化方式
		redis.setHashValueSerializer(valueSerializer);
		//连接器工厂
		redis.setConnectionFactory(connectionFactory);

		return redis;
	}

}

4.至此我们可以愉快的使用redisTemplate操作数据进行缓存,有趣的是,redis提供了专门的操作字符串的类stringRedisTemplate,感兴趣的可以通过下方的测试代码自行了解

 

编写测试类TestRedis,注意,其中的SysUser是我自定义的一个实体类,你可以另行自定义一个类用来测试,需要注意的是,redisTemplate在操作jdk1.8中的LocalDateTime时会出现Json转换错误,具体请看下篇文章:

package cn.jorian.jorianframework.redis;

import cn.jorian.jorianframework.core.system.entity.SysUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * @Author: jorian
 * @Date: 2019/5/14 14:44
 * @Description:
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestRedis {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 测试stringRedisTemplate
     */
    @Test
    public void strRedis(){
        stringRedisTemplate.opsForValue().set("name","张三aaa");
        String name = stringRedisTemplate.opsForValue().get("name");

        String tok = stringRedisTemplate.opsForValue().get("J-Token");
        log.info(name);
        log.info(tok);
    }

    /**
     * 测试redisTemplate
     */
    @Test
    public void objRedis(){
        SysUser sysUser1 = new SysUser();
        sysUser1.setId("1001");
        sysUser1.setUsername("jorian");
        sysUser1.setSex(1);

        SysUser sysUser2 = new SysUser();
        sysUser2.setId("1002");
        sysUser2.setUsername("jorian2");
        sysUser2.setSex(0);

        //缓存map形式
        redisTemplate.boundHashOps("testmap").put(sysUser1.getId(),sysUser1);
        //获取map
        List<SysUser> list=redisTemplate.boundHashOps("testmap").values();
        list.forEach(item->System.out.println(item));


        SysUser sysUser3 = new SysUser();
        sysUser3.setId("1003");
        sysUser3.setUsername("jorian3");
        sysUser3.setSex(0);
        //缓存对象
        redisTemplate.opsForValue().set(sysUser3.getId(), sysUser3);
        //获取对象
        System.out.println(redisTemplate.opsForValue().get("1002"));




    }




}

缓存结果:

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_38023579/article/details/102721354
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-08 11:33:46
  • 阅读 ( 903 )
  • 分类:Redis

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢