概述

先将Java对象转化成json字符串,然后Redis存储json字符串

实现过程

引入gson依赖

1
2
3
4
5
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>

使用到的方法

Jedis.rpop()

右侧弹出元素

Jedis.llen()

获取Redis的list长度

Jedis.rpush()

从右侧开始添加元素

Jedis.lrange()

获取全部元素集合

Gson.toJson()

Java对象转化成json

Gson.fromJson()

json转化成Java对象

Java代码

Fruit实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.ledao.jedis;

/**
* @author LeDao
* @company
* @create 2021-06-20 22:30
*/
public class Fruit {

/**
* 编号
*/
private Integer id;
/**
* 名称
*/
private String name;
/**
* 数量
*/
private Integer num;

public Fruit() {
}

public Fruit(String name, Integer num) {
this.name = name;
this.num = num;
}

public Fruit(Integer id, String name, Integer num) {
this.id = id;
this.name = name;
this.num = num;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getNum() {
return num;
}

public void setNum(Integer num) {
this.num = num;
}

@Override
public String toString() {
return "Fruit{" +
"id=" + id +
", name='" + name + '\'' +
", num=" + num +
'}';
}
}

测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.ledao.jedis;

import com.google.gson.Gson;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

/**
* @author LeDao
* @company
* @create 2021-06-20 7:47
*/
public class JedisTest {

public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.0.153", 6379);
jedis.auth("123456");
Fruit fruit1 = new Fruit(1, "苹果", 11);
Fruit fruit2 = new Fruit(2, "梨", 6);
Fruit fruit3 = new Fruit(3, "油桃", 8);
List<Fruit> fruitList = new ArrayList<>();
fruitList.add(fruit1);
fruitList.add(fruit2);
fruitList.add(fruit3);
//转化成json,便于redis存储Java对象
System.out.println("转化成json:");
Gson gson = new Gson();
for (Fruit fruit : fruitList) {
jedis.rpush("redisFruitList", gson.toJson(fruit));
}
//遍历
List<String> redisFruitList = jedis.lrange("redisFruitList", 0, -1);
for (String s : redisFruitList) {
System.out.println(s);
}
//Redis的list转化成Java对象
System.out.println("转化成Java对象:");
for (int i = 0; i < redisFruitList.size(); i++) {
Fruit fruit = gson.fromJson(redisFruitList.get(i), Fruit.class);
System.out.println(fruit.toString());
}
//清空redisFruitList
Long length = jedis.llen("redisFruitList");
if (length > 0) {
for (int i = 0; i < length; i++) {
jedis.rpop("redisFruitList");
}
}
//关闭连接
jedis.close();
}
}

结果

img