RedisCacheWriter和RedisTemplate有什么区别

时间:2018-11-16 09:34:11

标签: java spring spring-boot caching redis

JedisConnectionFactory jedisConnectionFactory() {
    RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("localhost", 6379);
    return new JedisConnectionFactory(redisStandaloneConfiguration);
}

案例1:使用RedisCacheWriter

public RedisCacheManager getRedisCacheManager(RedisConnectionFactory connectionFactory) {
    RedisCacheWriter cacheWriter = RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
    ClassLoader loader = this.getClass().getClassLoader();
    JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer(loader);
    SerializationPair<Object> pair = SerializationPair.fromSerializer(jdkSerializer);

    RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
    cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(3600));


    Map<String, RedisCacheConfiguration> initialCacheConfigurations = new HashMap<>();
    initialCacheConfigurations.put("order",cacheConfig.entryTtl(Duration.ofSeconds(1600)));


    RedisCacheManager cacheManager = new RedisCacheManager(cacheWriter, cacheConfig,initialCacheConfigurations);

    return cacheManager;
}

@Bean
public CacheManager cacheManager() {
    RedisCacheManager cacheManager=getRedisCacheManager(jedisConnectionFactory());
    log.info("CacheManager created ");
    return cacheManager;
}

情况2:RedisTemplate

@Bean
RedisTemplate<Object, Object> redisTemplate() {
    RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
    redisTemplate.setConnectionFactory(jedisConnectionFactory());
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    return redisTemplate;
}

@Bean
CacheManager cacheManager() {

    //JedisConnectionFactory cacheManager=jedisConnectionFactory();
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate());
    cacheManager.setDefaultExpiration(60);
    cacheManager.setUsePrefix(true);            
    return cacheManager;
}

RedisCacheManagerRedisTemplate有什么区别?这两个类之间存在显着的内存消耗差异。关于其内部存储在缓存中的实现吗?
Springboot 2.x具有RedisCacheWriter,但在Springboot 1.4.3中,我们必须使用RedisTemplate

0 个答案:

没有答案