Jedis连接Redis,Lettuce连接Redis
junit
junit
④11
test
redis.clients
jedis
2.9.0
org.projectlombok
lombok
1.1⑧12
@Test
public void Test1() {
// 连接Redis
Jedis jedis = new Jedis("localhost", 6379);
// 操作Redis - 因为Redis命令是什么,Jedis方法就是什么
jedis.set("name", "李四");
// 释放资源
jedis.close();
System.out.println(jedis.get("name"));
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private String name;
private String Date;
}
junit
junit
④12
test
redis.clients
jedis
2.9.0
org.projectlombok
lombok
1.1⑧12
org.springframework
spring-context
⑤2.⑥RELEASE
@Test
public void Test2() {
// 连接Redis
Jedis jedis = new Jedis("localhost", 6379);
// 准备key(String) -value (user)
String key = "user";
User value = new User("张三", "1999");
// 将key和value转换为byte[]
byte[] byteKey = SerializationUtils.serialize(key);
byte[] byteValue = SerializationUtils.serialize(value);
// 将key和value存储到Redis
jedis.set(byteKey, byteValue);
// 释放资源
jedis.close();
@Test
public void Test3() {
// 连接Redis
Jedis jedis = new Jedis("localhost", 6379);
// 准备一个key
String key = "user";
// 将key转换为字节数组类型
byte[] byteKey = SerializationUtils.serialize(key);
// jedis去redis中获取value
byte[] value = jedis.get(byteKey);
// 将value反序列化
User user = (User) SerializationUtils.deserialize(value);
System.out.println(user);
// 释放资源
jedis.close();
}
junit
junit
④12
test
redis.clients
jedis
2.9.0
org.projectlombok
lombok
1.1⑧12
org.springframework
spring-context
⑤2.⑥RELEASE
com.alibaba
fastjson
1.2.70
org.junit.jupiter
junit-jupiter
RELEASE
compile
@Test
public void test1(){
// 连接Redis
Jedis jedis = new Jedis("localhost",6379);
// 准备key(String) - value(User)
String key = "stringUser";
User value = new User("帅哥","19999");
// 使用fastJSON将value转换为json字符串
String stringValue = JSON.toJSONString(value);
// 存储到Redis中
jedis.set(key,stringValue);
// 释放资源
jedis.close();
}
@Test
public void test2(){
// 连接Redis
Jedis jedis = new Jedis("localhost",6379);
//准备一个key
String key = "stringUser";
//去Redis中查询value
String value = jedis.get(key);
//将value反序列化一个对象
User user = JSON.parseObject(value, User.class);
System.out.println("user = "◆ user);
// 释放资源
jedis.close();
}
以上就是土嘎嘎小编为大家整理的Java连接Redis,存储对象获取对象_)byte和json),连接池相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!