Jedis存储一个以byte[]的形式的对象到Redis
1.1 准备一个User实体类
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依赖
<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测试类,编写内容
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();
}
}
测试结果:
原文地址:https://blog.csdn.net/weixin_39033358/article/details/144005481
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!