java redis消息订阅与发布_java redis 订阅(subscribe/psubscribe)和发布 (publish)

1、首先引入Jar文件

redis.clients

jedis

2.9.0

二、代码实现 publish 发布消息、subscribe/psubscribe 订阅消息

package redis;

import redis.clients.jedis.*;

import java.util.HashSet;

public class Subscribe {

/**

* 机器群

*/

public static JedisCluster cluster = new JedisCluster(

new HashSet(){{

add(new HostAndPort("192.168.1.4", 7100));

add(new HostAndPort("192.168.1.5", 7101));

add(new HostAndPort("192.168.1.6", 7200));

add(new HostAndPort("192.168.1.7", 7201));

add(new HostAndPort("192.168.1.8", 7300));

add(new HostAndPort("192.168.1.9", 7301));

}});

/**

* 单机

*/

public static JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), "ip", 7001);

public static String topicLog = "log.*";

public static String topicLogInfo = "log.info";

public static String topicLogDebug = "log.info.debug";

public static String topicLogError = "log.info.debug.error";

/**

* 精确频道模式-订阅消息

* @param topic

*/

public static void sub(String topic){

new Thread(()->{

cluster.subscribe(new JedisPubSub() {

/**

* 完全匹配-接受消息

* @param channel 管道

* @param message 消息

*/

@Override

public void onMessage(String channel, String message) {

System.out.println("onMessage:" + message);

}

}, topic);

}).start();

}

/**

* 匹配频道模式-订阅消息

* @param topic

*/

public static void pSub(String topic){

new Thread(()->{

// 单机版使用 jedisPool.getResource().psubscribe

cluster.psubscribe(new JedisPubSub() {

/**

* 通配符匹配-接受消息

* @param channel 管道

* @param message 消息

*/

@Override

public void onPMessage(String pattern, String channel, String message) {

System.out.println("onPMessage:" + message);

}

}, topic);

}).start();

}

/**

* 发布消息

* @param topic 管道

* @param message 消息

*/

public static void publish(String topic,String message){

// 单机版使用 jedisPool.getResource().psubscribe

cluster.publish(topic,message);

}

public static void main(String[] args) throws InterruptedException {

sub(topicLog);

pSub(topicLog);

int i = 0;

// 1 秒发送一条消息

while (true){

Thread.sleep(1000);

i ++ ;

if(i == 1){

publish(topicLog,topicLog);

}else if(i == 2){

publish(topicLogDebug,topicLogDebug);

}else if(i == 3){

publish(topicLogInfo,topicLogInfo);

}else if(i == 4){

i = 0;

publish(topicLogError,topicLogError);

}

}

}

}

3、运行打印结果如下:

onPMessage:log.*

onMessage:log.*

onPMessage:log.info.debug

onPMessage:log.info

onPMessage:log.info.debug.error

onPMessage:log.*

onMessage:log.*

onPMessage:log.info.debug

onPMessage:log.info

onPMessage:log.info.debug.error

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值