配置redis的序列化,注入RedisTemplate方式
目录
- 配置Redis的序列化,注入RedisTemplate
- 使用redis,必须配置redis序列化类
- 总结
配置redis的序列化,注入RedisTemplate
public class RedisConfig { @Bean public RedisTemplate&编程客栈lt;String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2jsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setConnectionFactory(factory); //key序列化方式 template.setKeySerializer(redisSerializer); //value序列化 编程template.setValueSerializer(jackson2JsonRedisSerializer); //value hashmap序列化 template.setHashValueSerializer(jackson2JsonRedisSerializer); return template; }
使用redis,必须配置redis序列化类
package com.example.config; import org.springframework.context.annotation.Bean; import org.sprinXxBiNgframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.RedisSerializer; @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { // key 采用StringRedisSerializer // value 采用Gewww.devze.comnericJackson2JsonRedisSerializer RedisTemplate<String, Object> template = new RedisTemplate<>(); // 关闭启用默认配置 template.setEnableDefaultSerializer(false); // 连接工厂 template.setConnectionFactory(factory); // key 序列化方式 template.setKeySerializer(RedisSerializer.string()); // value 序列化方式 template.setValueSerializer(RedisSerializer.json()); // hash key 序列化方式 template.setHashKeySerializer(RedisSerializer.string()); // hash value 序列化方式 template.setHashValueSerializer(RedisSerializer.json()); //编程客栈 配置完成 template.afterPropertiesSet(); return template; } }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.4.0</version> </dependency>
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
精彩评论