最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Redis key-value乱码代码解决方法
时间:2022-06-29 10:40:00 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下Redis key-value乱码代码解决方法,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
redis 配置类
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.boot.SpringBootConfiguration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@SpringBootConfiguration
public class RedisConfig extends CachingConfigurerSupport {
/**
* 注入 RedisConnectionFactory
*/
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
return RedisCacheManager.builder(factory).build();
}
@Bean
public RedisTemplate functionDomainRedisTemplate() {
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 使用Jackson2JsonRedisSerialize 替换默认序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// 设置value的序列化规则和 key的序列化规则
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
当使用opsForValue() 存取String类型key,value情形
@Autowired
private StringRedisTemplate redisTemplate;
当使用opsForValue() 存取String类型key,自定义对象value情形
@Autowired
private RedisTemplate redisTemplate;
当使用hash结构时
@Autowired
private RedisTemplate redisTemplate;
BoundHashOperationsops = redisTemplate.boundHashOps("key1"); ops.put("key2",obj);
相关文章
- 魔兽世界12.0前夕奥法天赋怎么加点 03-28
- 极速漫画官方下载安装包在哪-极速漫画最新版本下载地址 03-28
- 洛克王国世界春团强度分析 洛克王国世界春团实战表现与阵容搭配详解 03-28
- 《烽烟》道士技能效果介绍 03-28
- AO3官网最新入口-AO3网页版直达链接 03-28
- 一帧秒创在线网页版-一帧秒创官网极速登录 03-28