首页  :: 新随笔  :: 管理

springboot Cacheable(redis),解决key乱码问题

Posted on 2018-11-20 20:32  季枫  阅读(2763)  评论(0编辑  收藏  举报
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mingyanliao
 * Date: 2018-11-20
 * Time: 下午7:52
 */
@Component
public class CacheConfig {

    //String json
    @Resource
    private RedisTemplate<String,String> jsonRedisTemplate;

    @Bean(name="redisWithSerial")
    public RedisTemplate<Object, Object> getRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        //json序列化方式
        GenericJackson2JsonRedisSerializer jsonRedisSerializer =new GenericJackson2JsonRedisSerializer();

        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(jsonRedisSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(jsonRedisSerializer);
        return redisTemplate;
    }
}

键值使用StringRedisSerializer,value使用GenericJackson2JsonRedisSerializer

 

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author myliao
 * @since 2018-11-20
 */
@Mapper
public interface MessageAutoanswerMapper extends BaseMapper<MessageAutoanswer> {

    @Cacheable(value = "panda_autoanswer",key="'m_'+#p0+'_'+#p1+'_'+#p2")
    @Select("select * from panda_wechat_message_autoanswer where wechat_id=#{wechatId} and subscribe_msg_type=#{msg_type} and msg_rule=#{rule}")
    public MessageAutoanswer getMessageAutoanswer(@Param("wechatId")Long wechatId, @Param("msg_type")String msg_type, @Param("rule")String rule);

    @CacheEvict(value = "panda_autoanswer",key="'m_'+#p0.wechatId+'_'+#p0.subscribeMsgType+'_'+#p0.msgRule")
    @Override
    public int insert(MessageAutoanswer messageAutoanswer);
}

  注意:Cacheable的value是指缓存名称,即redis里面的分组名称

智读 | 成都会领科技有限公司官网 | 智读App下载 | 每天听本书的博客 | |