当前位置: 首页 > 知识库问答 >
问题:

带有2.0x以上Spring data redis版本的RediscacheManager实例

何峰
2023-03-14

我之前使用的是Spring data Redis版本1.4.4。因为除了连接超时之外,我还必须配置读取超时,所以我已经将版本升级到2.1.6。但是现在我无法用RedisTemplate创建Rediscachemanager实例,因为spring data redis 2.0版不推荐使用它。可以有人请帮助一种方法来实现以下类似的配置(键/值序列化与RedisTemplate)与升级版本。

final JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
redisConnectionFactory.setHostName(redisHost);      
redisConnectionFactory.setTimeout(10000);
redisConnectionFactory.setPort(port);
redisConnectionFactory.setUsePool(true);
redisConnectionFactory.afterPropertiesSet();

@Bean(name = "redisCacheManager")
    public CacheManager cacheManager(final RedisTemplate<String,Object> redisTemplate) {
        final RedisCacheManager manager = new RedisCacheManager(redisTemplate());
        manager.setDefaultExpiration(Long.parseLong(expiryInSecs));
        return manager;
    }

    @Bean(name="redisTemplate")
    public RedisTemplate<String, Object> redisTemplate() {
        final RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        redisTemplate.setKeySerializer(stringRedisSerializer());
        redisTemplate.setHashKeySerializer(stringRedisSerializer());
        redisTemplate.setValueSerializer(stringRedisSerializer());
        redisTemplate.setHashValueSerializer(stringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

共有1个答案

臧正平
2023-03-14

如果将Spring Data Redis和Lettuce作为驱动程序(我推荐使用),您需要的配置如下:

  @Bean
  public RedisConnectionFactory connectionFactory() {
    LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
        .commandTimeout(Duration.ofSeconds(2))
        .shutdownTimeout(Duration.ZERO)
        .build();

    return new LettuceConnectionFactory(new RedisStandaloneConfiguration("localhost", 6379), clientConfig);
  }

  @Bean(name = "redisCacheManager")
  public CacheManager cacheManager(final RedisConnectionFactory factory) {
    Duration expiration = Duration.ofSeconds(12345);

    RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager
        .builder(factory)
        .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig().entryTtl(expiration));


    return builder.build();
  }

  @Bean(name="redisTemplate")
  public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
    redisTemplate.setConnectionFactory(factory);
    redisTemplate.setKeySerializer(stringRedisSerializer());
    redisTemplate.setHashKeySerializer(stringRedisSerializer());
    redisTemplate.setValueSerializer(stringRedisSerializer());
    redisTemplate.setHashValueSerializer(stringRedisSerializer());
    return redisTemplate;
  }
 类似资料: