redis存储数据优化

因为redis储存数据默认使用的时jdkjson,有两大问题:

    No1:存储的Object(Entity)需要实现序列化接口(implements Serializable);

    No2:存储的数据中有一些其他编码,导致可读性差;

所以为了解决以上的两个问题:

    将默认的jdkjson改为jsckson2json。代码如下:
package mall.config;

import client.AccessToken;
import client.RedisAccessTokenCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

@Configuration
public class redisConfig {

    @Autowired
    private RedisTemplate redisTemplate;

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory cf) {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(cf);
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        return redisTemplate;
    }

    @Bean
    public RedisAccessTokenCache redisAccessTokenCache(){
        RedisAccessTokenCache redisAccessTokenCache = new RedisAccessTokenCache();
        redisAccessTokenCache.setRedisTemplate(redisTemplate);
        return redisAccessTokenCache;
    }

}

你可能感兴趣的:(redis存储数据优化)