springboot 整合 redis

jedis 和 lettuce 都是用来连接 redis 的客户端,jedis 如果不使用连接池是非线程安全的,lettuce 使用 netty 线程安全且并发性能更好;

springboot 2.x 版本后 默认使用 lettuce

关于 StringRedisTemplate 和 RedisTemplate, 使用 StringRedisTemplate 即可, 不用管那些序列化问题, 因为 StringRedisTemplate 可以完成 Map, List, Set 等所有数据类型的操作

1,依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

2,redis 配置

# Redis 数据库索引(默认有16个分片,默认使用0)
spring.redis.database=1
# Redis 服务器地址
spring.redis.host=192.168.1.198
# Redis 服务器端口
spring.redis.port=6379
# Redis 服务器密码
spring.redis.password=111111
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0

3,自定义 redis 模板(如果使用 StringRedisTemplate, 这个模板可以不用配置 )

/**
 * .默认模板只能使用字符串,即 RedisTemplate<String, String>
 * .自定义模板使其能更多样
 * @author huanggy
 *
 */
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisCacheAutoConfiguration {
    @Bean
    public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Serializable> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

4,测试

@RestController
@RequestMapping("/test")
public class RedisController {
    
    @Autowired
    private StringRedisTemplate strRedis; // 操作字符串
    @Autowired
    private RedisTemplate<String, Serializable> redis; // 操作非字符串,比如对象
    
    @GetMapping("/str")
    public String testStr() {
        // 存入字符串
        strRedis.opsForValue().set("test1", "test1");
        // 取出字符串
        String str = strRedis.opsForValue().get("test1");
        return str;
    }
    
    @GetMapping("/obj")
    public String testObj() {
        // 必须实现 Serializable 接口
        User user = new User("李四", "女", new Date());
        // 存入对象
        redis.opsForValue().set("user1", user);
        // 取出对象
        User user1 = (User) redis.opsForValue().get("user1");
        return user1.toString();
    }
}

 

posted @ 2018-09-15 16:34  huanggy  阅读(226)  评论(0编辑  收藏  举报