赞
踩
RedisTemplate 对象在底层默认会转成字节,造成了内存的开销很大,这是他底层进行处理的,造成可读性差,如需要转成简单的字符串存储需要进行序列化的配置。
@Configuration public class RedisConfig { @Bean public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String,Object> template =new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer =new GenericJackson2JsonRedisSerializer(); //序列号工具 template.setKeySerializer(RedisSerializer.string());//字符串类型的Key为字符串类型 template.setHashKeySerializer(RedisSerializer.string());//哈希类型的key也为字符串类型 template.setValueSerializer(genericJackson2JsonRedisSerializer); //值的序列号 JSON template.setHashValueSerializer(genericJackson2JsonRedisSerializer); return template; } }
经过配置,值为转成的键值对类型
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private Integer age;
}
@RestController public class BasicController { @Autowired private RedisTemplate<String,Object> redisTemplate; @GetMapping("/hello") public User hello( ) { redisTemplate.opsForValue().set("user:login:123", new User("dpc",20)); //设置值 User user =(User)redisTemplate.opsForValue().get("user:login:123"); //取出值 return user; } }
返回结果
{“name”:“dpc”,“age”:20}
Redis存储结果
通过 “@class”: “com.example.demo.demos.web.User”,这个属性映射到实体类上,@class是JSON序列化类自动添加的,不可以去除。
当然也可以直接手动的序列化和反序列化节省内存空间。这样就不会出现改属性
Spring默认提供了一个StringRedisTemplate类,它的key和value的序列化方式默认就是String方式。省去了我们自定义RedisTemplate的过程,也就是说上面的的@Configuration配置类可以不用写了
@Autowired
private StringRedisTemplate stringRedisTemplate;
stringRedisTemplate.opsForValue().set("name","dpc");
String str =stringRedisTemplate.opsForValue().get("name");
@RestController public class BasicController { @Autowired private StringRedisTemplate stringRedisTemplate; private static final ObjectMapper obj=new ObjectMapper(); //手动序列化工具 @GetMapping("/hello") public User hello( ) throws JsonProcessingException { User user= new User("dpc",20); //实体类对象 String json =obj.writeValueAsString(user); //将实体类转成JSON 也就是字符串 stringRedisTemplate.opsForValue().set("user:login:123", json); //设置值 json格式写入 也就是字符串 User userMsg =obj.readValue(stringRedisTemplate.opsForValue().get("user:login:123"),User.class) ; //取出JSON字符串 转成java对象 return userMsg; } }
效果一致
原理是将对象转成JSON字符串,然后取出时将json字符串转成实体类就可以了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。