Jedis操作Redis6(四)

1. Jedis的用法

  1. 引入maven依赖

    1
    2
    3
    4
    5
    6
    <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
    <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>4.3.1</version>
    </dependency>
  2. 使用Redis的API操作redis

    Jedis工具类,这个类中包含了操作redis的所有方法

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
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* 使用Jedis测试常用的Redis API
* @author xiaoyuge
*/
public class AppTest {
Jedis jedis;

@Before
public void before() {
this.jedis = new Jedis("127.0.0.1", 6379);
jedis.auth("password"); //设置连接密码,如果没有省略
}

@After
public void after() {
this.jedis.close();
}

/**
* 测试Redis是否能连上
*/
@Test
public void ping() {
System.out.println(jedis.ping());
}

@Test
public void listTest() {
jedis.rpush("courses", "java", "php", "node", "js", "C++");
List<String> courses = jedis.lrange("courses", 0, -1);
for (String course : courses) {
System.out.print(course + ",");
}
//输出:java,php,node,js,C++
}

@Test
public void setTest() {
jedis.sadd("users", "tom", "jack", "lilei", "lilei");
Set<String> sets = jedis.smembers("users");
for (String set : sets) {
System.out.print(set + ",");
}
//输出:lilei,tom,jack
}

@Test
public void hashTest() {
jedis.hset("user:1001", "id", "1001");
jedis.hset("user:1001", "name", "xiaoyuge");
jedis.hset("user:1001", "age", "18");
Map<String, String> map = jedis.hgetAll("user:1001");
System.out.println(map); //{name=xiaoyuge, age=18, id=1001}
}

@Test
public void zsetTest() {
jedis.zadd("score", 100d, "maths");
jedis.zadd("score", 86d, "chinese");
jedis.zadd("score", 96d, "English");
List<String> list = jedis.zrange("score", 0, -1);
for (String s : list) {
System.out.print(s+",");
}
//输出:chinese,English,maths
}
@Test
public void subscribeTest() throws InterruptedException {
//subscribe 消息监听
jedis.subscribe(new JedisPubSub() {
@Override
public void onMessage(String channel, String message) {
System.out.print(channel+": "+message);
}
}, "channelName");
TimeUnit.SECONDS.sleep(1);
}
@Test
public void publishTest(){
jedis.publish("channelName","hello redis");
}
}