标签:redist get append object 直接 pen color hash ali
@Configuration @EnableCaching @EnableAutoConfiguration public class RedisConfiguration extends CachingConfigurerSupport { /** * 自定义生成key的规则 */ @Override public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object o, Method method, Object... objects) { //格式化缓存key字符串 StringBuilder sb = new StringBuilder(); //追加类名 sb.append(o.getClass().getName()); //追加方法名 sb.append(method.getName()); //遍历参数并且追加 for (Object obj : objects) { sb.append(obj.toString()); } System.out.println("调用Redis缓存Key : " + sb.toString()); return sb.toString(); } }; } /** * 采用RedisCacheManager作为缓存管理器 * @param connectionFactory */ @Bean public CacheManager cacheManager(RedisConnectionFactory connectionFactory) { RedisCacheManager redisCacheManager = RedisCacheManager.create(connectionFactory); return redisCacheManager; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate redisTemplate = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); //设置完这个可以直接将对象以json格式存入redis中,但是取出来的时候要用JSON.parseArray(Json.toJsonString(object),Object.class)解析一下 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); //调用后完成设置 redisTemplate.afterPropertiesSet(); return redisTemplate; } }
遇到的问题:原先在springboot启动类中添加叻@ComponentScan并且没有扫描@Configuration中的类,导致redisTemplate配置失败,添加扫描路径即可。
标签:redist get append object 直接 pen color hash ali
原文地址:https://www.cnblogs.com/imaye/p/10970783.html