← 返回首页
SpringBoot基础教程(三十二)
发表时间:2021-05-20 22:56:57
整合redis(lettuce版)

Springboot在1.x使用的是jedis框架,在2.x改为默认使用Lettuce框架与redis连接。

关于jedis跟lettuce的区别:

实现步骤:

1.添加springboot操作redis相关依赖。

<!--springboot2.x以后默认使用lettuce-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- redis依赖commons-pool 这个依赖一定要添加 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>


<!-- 测试库依赖 -->        
<dependency>           
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-test</artifactId>            
     <scope>test</scope>        
</dependency>

2.在application.yml添加lettuce配置

spring:
  redis:  
    port: 6379
    password: 123456  
    host: 127.0.0.1    
    lettuce:      
      pool:        
        max-active: 8 # 连接池大连接数(使用负值表示没有限制)        
        max-idle: 8 # 连接池中的大空闲连接        
        min-idle: 0 # 连接池中的小空闲连接        
        max-wait: 1000 # 连接池大阻塞等待时间(使用负值表示没有限制)      
      shutdown-timeout: 100   # 关闭超时时间

3.在config包下新建RedisConfig

package com.oracle.springbootdemo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.lang.reflect.Method;

@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    /**
     * 自定义缓存key的生成策略。默认的生成策略是看不懂的(乱码内容) 通过Spring 的依赖注入特性进行自定义的 配置注入并且此类是一个配置类可以更多程度的自定义配置    
     *
     * @return
     */
    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    /**
     *    
     * 缓存配置管理器
     */
    @Bean
    public CacheManager cacheManager(LettuceConnectionFactory factory) {
        //以锁写入的方式创建RedisCacheWriter对象        
        RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(factory);
        //创建默认缓存配置对象      
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        RedisCacheManager cacheManager = new RedisCacheManager(writer, config);
        return cacheManager;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // 在使用注解@Bean返回RedisTemplate的时候,同时配置hashKey与hashValue的序列化方式。        
        // key采用String的序列化方式        
        template.setKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson        
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的key也采用String的序列化方式        
        template.setHashKeySerializer(stringRedisSerializer);
        // hash的value序列化方式采用jackson        
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

后面的编写Controller的测试用例与上节jedis方式完全一样。RedisTemplate常用方法也与上小节完全相同,请大家自行参考。