Jedis存储一个以byte[]的形式的对象到Redis

1.1 准备一个User实体类
java 复制代码
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Date;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
    private Integer id;
    private String name;
    private Date birthday;
}
1.2 导入Maven依赖
xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<!--  切换 jedis 作为操作redis的底层客户端-->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
1.3 创建TestSetByteArray测试类,编写内容
java 复制代码
import org.springframework.util.SerializationUtils;
import redis.clients.jedis.Jedis;

import java.util.Date;

public class TestSetByteArray {
    // Redis服务器信息
    private static final String REDIS_HOST = "192.168.200.141";
    private static final int REDIS_PORT = 6379;
    private static final String REDIS_PASSWORD = "sl183691";

    public static void main(String[] args) {
        //1. 连接Redis
        Jedis jedis = new Jedis(REDIS_HOST, REDIS_PORT);
        jedis.auth(REDIS_PASSWORD);

        //2.1 准备key(String)-value(User)
        String key = "user";
        User value = new User(1, "张三", new Date());
        //2.2 将key和value转换为byte[]
        byte[] byteKey = SerializationUtils.serialize(key);
        byte[] byteValue = SerializationUtils.serialize(value);
        //2.3 将key和value存储到Redis
        jedis.set(byteKey, byteValue);
        System.out.println("===================================================");

        //3. 获取操作结果
        //3.1 jedis去Redis中获取value
        byte[] value2 = jedis.get(byteKey);
        //3.2 将value反序列化为User对象
        User user = (User) SerializationUtils.deserialize(value2);
        //3.3 输出
        System.out.println("user:" + user);

        //4. 释放资源
        jedis.close();
    }
}

测试结果:

相关推荐
2401_8321319511 分钟前
Python单元测试(unittest)实战指南
jvm·数据库·python
打工的小王1 小时前
redis(四)搭建哨兵模式:一主二从三哨兵
数据库·redis·缓存
Anarkh_Lee1 小时前
【小白也能实现智能问数智能体】使用开源的universal-db-mcp在coze中实现问数 AskDB智能体
数据库·人工智能·ai·开源·ai编程
橘子132 小时前
MySQL用户管理(十三)
数据库·mysql
Dxy12393102162 小时前
MySQL如何加唯一索引
android·数据库·mysql
我真的是大笨蛋2 小时前
深度解析InnoDB如何保障Buffer与磁盘数据一致性
java·数据库·sql·mysql·性能优化
怣502 小时前
MySQL数据检索入门:从零开始学SELECT查询
数据库·mysql
shengli7222 小时前
机器学习与人工智能
jvm·数据库·python
2301_765703142 小时前
Python迭代器(Iterator)揭秘:for循环背后的故事
jvm·数据库·python
奋进的芋圆2 小时前
Spring Boot 实现三模安全登录:微信扫码 + 手机号验证码 + 邮箱验证码
spring boot·redis·微信