spring boot data RedisTemplate 序列化问题

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Jackson2JsonRedisSerializer;


@Configuration public class RedisTemplateConfiguration { @Bean public RedisTemplate < String , Object > redisTemplate ( RedisConnectionFactory redisConnectionFactory ) { Jackson2JsonRedisSerializer < Object > jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer < Object > ( Object . class ) ; ObjectMapper om = new ObjectMapper () ; om . setVisibility ( PropertyAccessor .ALL , JsonAutoDetect . Visibility .ANY ) ; om . enableDefaultTyping ( ObjectMapper . DefaultTyping .NON_FINAL ) ; jackson2JsonRedisSerializer . setObjectMapper (om ) ; RedisTemplate < String , Object > template = new RedisTemplate < String , Object > () ; template . setConnectionFactory ( redisConnectionFactory ) ; template . setKeySerializer (jackson2JsonRedisSerializer ) ; template . setValueSerializer (jackson2JsonRedisSerializer ) ; template . setHashKeySerializer (jackson2JsonRedisSerializer ) ; template . setHashValueSerializer (jackson2JsonRedisSerializer ) ; template . afterPropertiesSet () ; // RedisSerializer stringSerializer = new StringRedisSerializer(); // template.setKeySerializer(stringSerializer ); // template.setValueSerializer(stringSerializer ); // template.setHashKeySerializer(stringSerializer ); // template.setHashValueSerializer(stringSerializer ); return template ; }



public class ServiceImp implements Service{

@Autowired
private RedisTemplate redisTemplate;

private String getAccessTokenByParam(String appId,String appSecret){
    String accessToken = null;
    //redis 获取token
    Object tokenObj = null;
    try {
        tokenObj = redisTemplate.opsForValue().get(appId+appSecret);
    }catch(Exception e){  
        e.printStackTrace(); 
    }
    if(null == tokenObj){
        Token token = WeChatUtils.getToken(appId, appSecret);
        if(null != token){
            accessToken = token.getAccessToken();
            redisTemplate.opsForValue().set(appId+appSecret,accessToken,TTIME_OUT, TimeUnit.SECONDS);
        }else {
            return null;
        }
    }else{
        accessToken = tokenObj.toString();
    }
    return accessToken;
}

}

第一步 配置config 注册bean至spring ioc
第二步 service 自动装配 redisTemplate


你可能感兴趣的:(Redis)