SpringBoot集成Redis,使用RedisTemple存储对象使用纯JSON格式
1、对象使用Json序列化
import com. alibaba. fastjson. JSON ;
import com. alibaba. fastjson. parser. ParserConfig ;
import com. alibaba. fastjson. serializer. SerializerFeature ;
import org. springframework. data. redis. serializer. RedisSerializer ;
import org. springframework. data. redis. serializer. SerializationException ; import java. nio. charset. Charset ; public class FastJsonRedisSerializer < T > implements RedisSerializer < T > { private static final Charset DEFAULT_CHARSET = Charset . forName ( "UTF-8" ) ; private Class < T > clazz; public FastJsonRedisSerializer ( Class < T > clazz) { super ( ) ; this . clazz = clazz; } @Override public byte [ ] serialize ( T t) throws SerializationException { if ( null == t) { return new byte [ 0 ] ; } if ( t instanceof String ) { return t. toString ( ) . getBytes ( ) ; } return JSON . toJSONString ( t, SerializerFeature. NotWriteRootClassName ) . getBytes ( DEFAULT_CHARSET ) ; } @Override public T deserialize ( byte [ ] bytes) throws SerializationException { if ( null == bytes || bytes. length <= 0 ) { return null ; } String str = new String ( bytes, DEFAULT_CHARSET ) ; ParserConfig . getGlobalInstance ( ) . setAutoTypeSupport ( false ) ; return JSON . parseObject ( str, clazz) ; }
}
创建RedisTemple对象
import com. fasterxml. jackson. annotation. JsonAutoDetect ;
import com. fasterxml. jackson. annotation. PropertyAccessor ;
import com. fasterxml. jackson. databind. ObjectMapper ;
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. StringRedisSerializer ; @Configuration
public class RedisConfig { @Bean public RedisTemplate < String , Object > redisTemplate ( @Autowired ( required = false ) RedisConnectionFactory redisConnectionFactory) { ObjectMapper objectMapper = new ObjectMapper ( ) ; objectMapper. setVisibility ( PropertyAccessor . ALL , JsonAutoDetect. Visibility . ANY ) ; objectMapper. enableDefaultTyping ( ObjectMapper. DefaultTyping . NON_FINAL ) ; FastJsonRedisSerializer < Object > fastJsonRedisSerializer = new FastJsonRedisSerializer < > ( Object . class ) ; RedisTemplate < String , Object > redisTemplate = new RedisTemplate < > ( ) ; redisTemplate. setConnectionFactory ( redisConnectionFactory) ; redisTemplate. setKeySerializer ( new StringRedisSerializer ( ) ) ; redisTemplate. setValueSerializer ( fastJsonRedisSerializer) ; redisTemplate. setHashKeySerializer ( new StringRedisSerializer ( ) ) ; redisTemplate. setHashValueSerializer ( fastJsonRedisSerializer) ; redisTemplate. afterPropertiesSet ( ) ; return redisTemplate; }
}