redis(四)----发布订阅

发布订阅(pub/sub)是一种消息通信模式,主要的目的是解耦消息发布者和消息订阅者之间的耦合。pub /sub不仅仅解决发布者和订阅者直接代码级别耦合,也解决两者在物理部署上的耦合。废话不多说,直接上代码

public class PubSub {
private final String redisChanel1 = "redisChanel1";
private final String redisChanel2 = "redisChanel2"; private String redisHost = "10.5.31.155";
private int redisPort = 6379;
private Jedis redis; @Before
public void before() {
redis = new Jedis(redisHost, redisPort);
} @Test
public void pubChanel1() throws InterruptedException {
for (int i = 0; i < 1000; i++) {
// 通过redis的“redisChanel1”频道发布消息
redis.publish(redisChanel1, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 第" + i + "条消息");
// 消息发布后随即sleep 0-2s
Thread.sleep(Math.round(Math.floor(Math.random() * 2000)));
}
} @Test
public void pubChanel2() throws InterruptedException {
for (int i = 0; i < 1000; i++) {
// 通过redis的“redisChanel2”频道发布消息
redis.publish(redisChanel2, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 第" + i + "条消息");
// 消息发布后随即sleep 0-2s
Thread.sleep(Math.round(Math.floor(Math.random() * 2000)));
}
} @Test
public void sub() {
// 同时订阅“redisChanel1”频道和“redisChanel2”频道的消息并输出到控制台
redis.subscribe(new JedisPubSub() {
@Override
public void onMessage(String channel, String message) {
System.out.println(channel + "-->" + message);
}
}, redisChanel1, redisChanel2);
} @After
public void after() {
redis.close();
} }

先运行sub方法,再运行pubChanel1、pubChanel2方法,可以看到输出:

redisChanel1-->2018-09-27 18:04:34 第0条消息
redisChanel1-->2018-09-27 18:04:35 第1条消息
redisChanel2-->2018-09-27 18:04:36 第0条消息
redisChanel2-->2018-09-27 18:04:36 第1条消息
redisChanel1-->2018-09-27 18:04:36 第2条消息
redisChanel1-->2018-09-27 18:04:38 第3条消息
redisChanel1-->2018-09-27 18:04:38 第4条消息
redisChanel2-->2018-09-27 18:04:38 第2条消息
redisChanel1-->2018-09-27 18:04:39 第5条消息
...

先运行pubChanel1、pubChanel2方法,再运行sub方法,可以看到输出:

redisChanel2-->2018-09-27 18:05:56 第2条消息
redisChanel1-->2018-09-27 18:05:57 第3条消息
redisChanel1-->2018-09-27 18:05:57 第4条消息
redisChanel2-->2018-09-27 18:05:57 第3条消息
redisChanel1-->2018-09-27 18:05:58 第5条消息
redisChanel2-->2018-09-27 18:05:58 第4条消息
redisChanel2-->2018-09-27 18:05:59 第5条消息
...

也就说明:在消费者下线的情况下,生产者生产的消息会丢失。如果要避免这种问题,需要使用专业的消息队列如rabbitMQ等。

上一篇:leetcode(88)_1749_medium_任意子数组和的绝对值的最大值_python


下一篇:sql server 2008安装过程中服务器配置出错