码迷,mamicode.com
首页 > 编程语言 > 详细

springboot+mybatis+redis

时间:2019-06-03 23:32:43      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:redist   get   append   object   直接   pen   color   hash   ali   

  1. redis类似乱码问题,可修redisTemplate 的配置,配置如下
    @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配置失败,添加扫描路径即可。

springboot+mybatis+redis

标签:redist   get   append   object   直接   pen   color   hash   ali   

原文地址:https://www.cnblogs.com/imaye/p/10970783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!