springboot中Redis的Lettuce客户端和jedis客户端

1、引入客户端依赖

        <!--jedis客户端依赖-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>


        <!--默认使用lettuce客户端-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.1.4.RELEASE</version>
        </dependency>

2、RedisTemplate 自定义对象定义

@Configuration
public class BackupRedisConfig {

    //Redis数据库索引
    @Value("${spring.redis.database}")
    Integer database;
    //Redis服务器地址
    @Value("${spring.backup.redis.host}")
    String host;
    // Redis服务器连接端口
    @Value("${spring.redis.port}")
    Integer port;
    //Redis服务器连接密码
    @Value("${spring.backup.redis.password}")
    String password;

    //连接池最大连接数(使用负值表示没有限制)
    @Value("${spring.redis.lettuce.pool.max-active}")
    Integer maxActive;
//连接池最大阻塞等待时间(使用负值表示没有限制)
    @Value("${spring.backup.redis.lettuce.pool.max-wait}")
    Long maxWait;
    //连接池中的最大空闲连接
    @Value("${spring.redis.lettuce.pool.max-idle}")
    Integer maxIdle;
    //连接池中的最小空闲连接
    @Value("${spring.redis.lettuce.pool.min-idle}")
    Integer minIdle;
    // 连接超时时间(毫秒)
    @Value("${spring.backup.redis.timeout}")
    String timeout;



    @Bean("backupRedisTemplate")
    public RedisTemplate backupRedisTemplate() {
        //lettuce 客户端连接池配置
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(maxActive);
        poolConfig.setMaxWaitMillis(maxWait);
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        //lettuce 客户端配置
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setDatabase(database);
        config.setHostName(host);
        config.setPort(port);
        config.setPassword(password);

//      lettuce创建工厂
//        LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder().poolConfig(poolConfig).build();
//        LettuceConnectionFactory factory = new LettuceConnectionFactory(config, clientConfiguration);
//        factory.afterPropertiesSet();

        //jedis连接池配置
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWait);
        jedisPoolConfig.setMaxTotal(maxActive);

        //创建jedis工厂
        JedisConnectionFactory factory = new JedisConnectionFactory(config);
        factory.setPoolConfig(jedisPoolConfig);

        //构建reids客户端,只能指定其中1个工厂
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new FastJsonRedisSerializer<>(Object.class));
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }


}

3、RedisTemplate 默认链接对象,指定reids序列化方式,自定义缓存注解读写机制@Cacheable

  a、实现RedisSerializer接口

public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Class<T> clazz;

    // 解决fastJson autoType is not support错误
    static {
        ParserConfig.getGlobalInstance().addAccept("com.qingclass.yiban");
    }

    public FastJsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    @Nullable
    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Nullable
    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
        return JSON.parseObject(str, clazz);
    }

}

b、指定reids序列化方式,自定义缓存注解读写机制@Cacheable

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 设置reids 链接序列化
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate redisTemplate(LettuceConnectionFactory factory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(getJsonRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    /**
     * 指定缓存管理器,读写机制
     * @param factory
     * @return
     */
    @Bean
    public CacheManager cacheManager(LettuceConnectionFactory factory) {
        // 默认过期时间1小时
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().disableKeyPrefix()
                .entryTtl(Duration.ofHours(CacheTtl.ONE_HOUR.getTime()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(getJsonRedisSerializer()));
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(factory))
                .cacheDefaults(redisCacheConfiguration)
                .withInitialCacheConfigurations(getRedisCacheConfigurationMap())
                .build();
    }

    private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>(CacheTtl.values().length);
        for (CacheTtl cacheTtl : CacheTtl.values()) {
            redisCacheConfigurationMap.put(cacheTtl.getValue(), this.getRedisCacheConfigurationWithTtl(cacheTtl.getTime()));
        }
        return redisCacheConfigurationMap;
    }

    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer hours) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().disableKeyPrefix()
                .entryTtl(Duration.ofHours(hours))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(getJsonRedisSerializer()));
        return redisCacheConfiguration;
    }

    private FastJsonRedisSerializer getJsonRedisSerializer() {
        return new FastJsonRedisSerializer<>(Object.class);
    }

}
* spring boot在1.x.x的版本时默认使用的jedis客户端,
* 现在是2.x.x版本默认使用的lettuce客户端
* 详情链接 https://www.cnblogs.com/taiyonghai/p/9454764.html
原文地址:https://www.cnblogs.com/niunafei/p/12766671.html