前提纪要:因为业务变动,需要在原先只支持protobuf的前提序列化的前提下,新增正常的序列化读取数据所以在原先的基础上进行优化。文章用于记忆。
话不多说直接上代码
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
@Import({RedisAutoConfiguration.class})
@Slf4j
public class ProtobufRedisTemplateConfig {private final LettuceConnectionFactory lettuceConnectionFactory;public ProtobufRedisTemplateConfig (LettuceConnectionFactory lettuceConnectionFactory) {this.lettuceConnectionFactory = lettuceConnectionFactory;}@Beanpublic RedisTemplate<Object, Object> protobufRedisTemplate() {RedisTemplate<Object, Object> template = new RedisTemplate<>();template.setConnectionFactory(lettuceConnectionFactory);RedisSerializer<byte[]> byteRedisSerializer = new RedisSerializer<byte[]>() {@Overridepublic byte[] serialize(byte[] bytes) throws SerializationException {return new byte[0];}@Overridepublic byte[] deserialize(byte[] bytes) {return bytes;}};template.setKeySerializer(byteRedisSerializer);template.setValueSerializer(byteRedisSerializer);template.setHashKeySerializer(byteRedisSerializer);template.setHashValueSerializer(byteRedisSerializer);template.afterPropertiesSet();log.warn("the Lettuce-protobuf starting success, date is -->" + new Date());return template;}@Beanpublic RedisTemplate<String, Object> jsonRedisTemplate() {RedisTemplate redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(lettuceConnectionFactory);// 使用Jackson2JsonRedisSerializer 替换默认的JDKSerializationRedisSerializer 来序列化和反序列化redis 的value值Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);redisTemplate.setHashKeySerializer(new StringRedisSerializer());// hash的value序列化方式采用jacksonredisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);redisTemplate.afterPropertiesSet();return redisTemplate;}
}
使用
@Autowired@Qualifier("protobufRedisTemplate")private RedisTemplate<Object, Object> protobufRedisTemplate;@Autowired@Qualifier("jsonRedisTemplate")private RedisTemplate<String, Object> redisTemplate;