因为不设置序列化redis在Redis Desktop Manager中存储的数据是默认jdk序列化的,我们看不懂,我们需要把他改成jackson序列化,这样存在这个可视化工具里面我们才能看的懂,也方便调用。
import com.springboot.bootcache.bean.Department;
import com.springboot.bootcache.bean.Employee;
import com.springboot.bootcache.bean.Goods;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class Redis {
//自定义操作employee的
@Bean
public RedisTemplate<Object, Employee> empRedisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
template.setDefaultSerializer(ser);
return template;
}
CacheManagerCustomizers可以来定制缓存的一些规则
当我们在redis可视化工具存储数据的时,如果我们不设置key值,key值就是默认的参数值,我们可以通过CacheManagerCustomizers可以来定制缓存的一些规则,
例如:我设置是使用前缀,默认会将CacheName作为key的前缀。如下图
@Primary //将某个缓存管理器作为默认的
@Bean
public RedisCacheManager employeeCacheManager(RedisTemplate<Object, Employee> empRedisTemplate){
RedisCacheManager cacheManager = new RedisCacheManager(empRedisTemplate);
//key多了一个前缀
//使用前缀,默认会将CacheName作为key的前缀
cacheManager.setUsePrefix(true);
// Map<String,Long> expires=new HashMap<>();
// expires.put("1m",60*1L);
// cacheManager.setExpires(expires);
return cacheManager;
}