13.StringRedisTemplete使用

上一篇说到改变了RedisTemplate的默认序列化器后,在redis中存入Java对象后,在redis中的呈现是:会记录类的字节码

这也是代码中可以强制装换为对应的java对象的原因:

复制代码
@Test
void testStudent() {
    redisTemplate.opsForValue().set("student:100", new Student("小明", 22));
    Student student = (Student) redisTemplate.opsForValue().get("student:100");
    System.out.println("student="+student);
}

存在的问题:

因为每个对象都要存入class,随着对象越来越多也会带来内存额外的开销。

所以,为了节省空间,不会使用json的序列化器来处理value,而是统一使用String序列化器,要求只能存储String类型的key和value,当需要存储java对象时,手动完成对象的序列化和反序列化。

Spring默认提供了一个StringRedisTemplate类,它的key和value的序列化方式默认就是String方式,省去了我们自己定义RedisTemplate过程:

java 复制代码
@Autowired
    private StringRedisTemplate stringRedisTemplate;
    //json工具
    ObjectMapper objectMapper = new ObjectMapper();

    @Test
    void testJava() throws JsonProcessingException {
        //手动将java对象转成json字符串
        String studentJson = objectMapper.writeValueAsString(new Student("晓东", 11));
        //写入一条数据到redis
        stringRedisTemplate.opsForValue().set("student:200",studentJson);
        //读取数据
        String studentJsonStr = stringRedisTemplate.opsForValue().get("student:200");
        //手动将json数据转成java对象
        Student student = objectMapper.readValue(studentJsonStr, Student.class);
        System.out.println("student="+student);
    }

存入单个key-value、key-java对象都是可以的。

操作Hash类型的数据

java 复制代码
 @Test
    void testHash() {
        stringRedisTemplate.opsForHash().put("user:400", "name", "张大大");
        stringRedisTemplate.opsForHash().put("user:400", "age", "18");
        //获取key对应所有的hash key value
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries("user:400");
        entries.forEach((key, value)-> System.out.println(key+"--"+value));
    }

这里注意存入hash的value需要时String类型,比如上面的18,不能写数字18,而是要写字符串18。

相关推荐
小碗羊肉11 分钟前
【Redis | 第六篇】Redisson
数据库·redis·缓存
夜勤月16 分钟前
AQS 与 ThreadPoolExecutor 深度拆解:JDK 高并发底层设计精髓
android·java·开发语言
phltxy23 分钟前
Spring AI 应用开发
java·人工智能·spring
码不停蹄的玄黓25 分钟前
Arthas 线上问题排查实战:CPU过高、频繁GC
java
Michaelwubo29 分钟前
swagger全集通+mock(prism)
java
ss2731 小时前
ai编程Trae cn生成图书管理系统(1)
java·数据库·spring boot·python·flask·fastapi
如竟没有火炬1 小时前
寻找峰值——二分
java·开发语言·数据结构·python·算法·散列表
Lumbrologist1 小时前
【C++】零基础入门 · 第 17 节:多线程编程基础
java·c++·算法
AwakeFantasy1 小时前
关于Codex中转站生图比例问题的解决记录
数据库·redis·缓存
tkevinjd1 小时前
事务、ACID与隔离
java·数据库·sql