配置redis缓存 并设置值序列化为json格式
//springboot会自动注入该bean
@Bean
public RedisConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration =
new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setHostName(host);
redisStandaloneConfiguration.setPort(port);
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration);
return jedisConnectionFactory;
}
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
//默认1
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()));
config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()));
config = config.disableCachingNullValues();
RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.transactionAware()
.build();
log.debug("自定义RedisCacheManager加载完成");
return redisCacheManager;
}
//键得序列号
private RedisSerializer<String> keySerializer() {
return new StringRedisSerializer();
}
//值得序列号
private RedisSerializer<Object> valueSerializer() {
return new GenericJackson2JsonRedisSerializer();
}
spring使用本地缓存配置 注:sprinboot导入缓存场景启动器自动为本地缓存 不需要该配置
/** * 使用本地缓存 */
@Bean
public CacheManager cacheManager(List<Cache> caches) {
SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
simpleCacheManager.setCaches(caches);
return simpleCacheManager;
}
@Bean
public ConcurrentMapCacheFactoryBean dictCkind() {
ConcurrentMapCacheFactoryBean stockDetail = new ConcurrentMapCacheFactoryBean();
// 如果用户设置名称为stockDetail的缓存,则需要添加这样的一个bean
//stockDet
return stockDetail;
}
spring中配置maven
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>