pom.xml
<!--Jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
MyJedisPubSub.java
public class MyJedisPubSub extends JedisPubSub {
@Override
public void onMessage(String channel, String message) {
System.out.println(String.format(
"我是线程'%s':收到消息,具体频道为'%s', 得到的消息为'%s'",
Thread.currentThread().getId(), channel, message
));
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
System.out.println(String.format(
"我是线程'%s':订阅成功,具体频道为'%s', 目前订阅频道总数为'%s'",
Thread.currentThread().getId(), channel, subscribedChannels
));
}
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
System.out.println(String.format(
"我是线程'%s':取消频道订阅!,具体频道为'%s', 目前订阅频道总数为'%s'",
Thread.currentThread().getId(), channel, subscribedChannels
));
}
}
App.java
public class App {
private static final MyJedisPubSub myJedisPubSub1 = new MyJedisPubSub();
private static final MyJedisPubSub myJedisPubSub2 = new MyJedisPubSub();
public static void main(String[] args) {
//建立连接池
JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), "localhost");
//1号订阅频道线程
new Thread(new Runnable() {
@Override
public void run() {
//try-with-resources 格式(无需手动释放资源)
try (Jedis jedis = jedisPool.getResource()) {
jedis.subscribe(myJedisPubSub1, "hello");
}
}
}).start();
//2号订阅频道线程
new Thread(new Runnable() {
@Override
public void run() {
//try-with-resources 格式(无需手动释放资源)
try (Jedis jedis = jedisPool.getResource()) {
jedis.subscribe(myJedisPubSub2, "hello");
}
}
}).start();
//等待3s
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//1号订阅其他频道
myJedisPubSub1.subscribe("other", "otherother");
//1号取消订阅
myJedisPubSub1.unsubscribe("other");
//等待3s
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//获取一个新的redis客户端,发布一条消息
try (Jedis jedis = jedisPool.getResource()) {
jedis.publish("hello", "hi 大家好");
}
//销毁连接池
jedisPool.destroy();
//退出程序
System.exit(0);
}
}
执行输出
我是线程'14':订阅成功,具体频道为'hello', 目前订阅频道总数为'1'
我是线程'13':订阅成功,具体频道为'hello', 目前订阅频道总数为'1'
我是线程'13':订阅成功,具体频道为'other', 目前订阅频道总数为'2'
我是线程'13':订阅成功,具体频道为'otherother', 目前订阅频道总数为'3'
我是线程'13':取消频道订阅!,具体频道为'other', 目前订阅频道总数为'2'
我是线程'13':收到消息,具体频道为'hello', 得到的消息为'hi 大家好'
我是线程'14':收到消息,具体频道为'hello', 得到的消息为'hi 大家好'