第一步:建立一个监听类,继承JedisPubSub
package work;
import redis.clients.jedis.JedisPubSub;
/**
* 监听
* author:songyan
* date: 2019/10/17
**/
public class MyListener extends JedisPubSub {
private String subName;
public MyListener(String subName) {
this.subName = subName;
}
// 取得订阅的消息后的处理
public void onMessage(String channel, String message) {
System.out.println(String.format("订阅者:"+ subName + "接收消息,频道:%s,消息%s" , channel , message));
}
// 初始化订阅时候的处理
public void onSubscribe(String channel, int subscribedChannels) {
System.out.println(String.format("订阅者:"+ subName + "订阅频道成功,频道:%s,订阅频道数%d" , channel , subscribedChannels));
}
// 取消订阅时候的处理
public void onUnsubscribe(String channel, int subscribedChannels) {
System.out.println(String.format("订阅者:"+ subName + "取消订阅成功,频道名称:%s,订阅频道数%d",channel , subscribedChannels));
}
}
第二步:建立一个Publisher (发布者)
package work;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* 发布
* author:songyan
* date: 2019/10/17
**/
public class Publisher extends Thread {
//定义一个连接池
private final JedisPool jedisPool;
private String chanelName;
public Publisher(JedisPool jedisPool, String chanelName) {
this.jedisPool = jedisPool;
this.chanelName = chanelName;
}
@Override
public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Jedis jedis = jedisPool.getResource();
while (true) {
String line = null;
try {
line = reader.readLine();
if (!"quit".equals(line)) {
jedis.publish(chanelName, line);
System.out.println("发布者频道发布成功,频道名称:" + chanelName);
} else {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
第三步:创建一个订阅者类,用来控制订阅者订阅消息频道
---恢复内容结束---
标签:订阅,频道,String,subName,import,Jedis,public
来源: https://www.cnblogs.com/excellencesy/p/11696580.html