Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。
Redis 客户端可以订阅任意数量的频道。 (推荐学习:Redis视频教程)
Redis提供了发布订阅功能,可以用于消息的传输,Redis的发布订阅机制包括三个部分,发布者,订阅者和Channel。
发布者和订阅者都是Redis客户端,Channel则为Redis服务器端,发布者将消息发送到某个的频道,订阅了这个频道的订阅者就能接收到这条消息。Redis的这种发布订阅机制与基于主题的发布订阅类似,Channel相当于主题。
1,引入Jedis
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
2,具体实现代码
package com.hcmony.sword.redis; import org.apache.commons.lang3.StringUtils; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPubSub; /** * <h3>Shenjue.java基本描述</h3> * <p></p> * * @author hcmony * @since V1.0.0, 2019/05/06 20:07 */ public class RedisMQ { private static final String TOPIC="TOPIC"; private final JedisPool jedisPool; public RedisMQ(JedisPool jedisPool) { this.jedisPool = jedisPool; } /** * 发布消息 * @param topic * @param messge */ public void publish(String topic ,String messge){ Jedis jedis = null; if (StringUtils.isBlank(topic)){ topic=TOPIC; } try { jedis = jedisPool.getResource(); jedis.publish(topic,messge); } finally { if (null != jedis) { jedis.close(); } } } /** * 订阅消息 * @param topic * @param jedisPubSub */ public void subscribe(String topic,JedisPubSub jedisPubSub){ Jedis jedis = null; if (StringUtils.isBlank(topic)){ topic=TOPIC; } try { jedis = jedisPool.getResource(); jedis.subscribe(jedisPubSub,topic); } finally { if (null != jedis) { jedis.close(); } } } public static void main(String[] args) { //默认连接本地redis, // loclhost:6379 JedisPool jedisPool = new JedisPool(); RedisMQ publish = new RedisMQ(jedisPool); new Thread(new Runnable() { @Override public void run() { publish.subscribe("PID",new MyjedisPubSub()); } }).start(); for (int i=0;i<100;i++){ publish.publish("PID","messge"+i); } } public static class MyjedisPubSub extends JedisPubSub { @Override public void onMessage(String channel, String message) { System.out.println("-------channel is "+channel+" message is "+message); } } }