1. 基础
- spring定义了缓存抽象,并提供了缓存抽象的实现,比如
基于ConcurrentMap
、redis实现的缓存
。这里以redis实现的缓存抽象为例,并且结合springboot对该缓存抽象的自动配置为例 - 缓存管理器
RedisCacheManager
,决定了序列化和反序列化 - 序列化策略,使用
RedisCacheConfiguration
配置
2. 自定义序列化器
RedisSerializer
有多种实现,这里使用最后一个jackson
package cn.covey.cache.config;
import cn.covey.cache.entry.Account;
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.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
@Configuration
public class RedisCacheConfig {
@Bean
public RedisCacheManager accountRedisCacheManager(RedisConnectionFactory redisConnectionFactory){
// 1. RedisCacheConfiguration
RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(
new Jackson2JsonRedisSerializer<Account>(Account.class)));
// 2. RedisCacheManager
return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(configuration).build();
}
}
在redis中查看