Jedis存储一个-以String的形式的对象到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>
<!-- 导入fastJSON -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
1.3 创建TestSetString测试类,编写内容
import com.alibaba.fastjson.JSON;
import redis.clients.jedis.Jedis;
import java.util.Date;
public class TestSetString {
// 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 stringKey = "stringUser";
User value = new User(2, "李四", new Date());
//2.2 使用fastJSON将value转化为json字符串
String stringValue = JSON.toJSONString(value);
//2.3 将key和value存储到Redis中
jedis.set(stringKey, stringValue);
System.out.println("===================================================");
//3. 获取操作结果
//3.1 jedis去Redis中获取value
String value2 = jedis.get(stringKey);
//3.2 将value反序列化为User对象
User user = JSON.parseObject(value2, User.class);
//3.3 输出
System.out.println("user:" + user);
//4. 释放资源
jedis.close();
}
}
测试结果: