Redis publish and subscribe (pub/sub) is a message communication model: the sender (pub) sends messages and the subscribers (sub) receive messages.
Redis clients can subscribe to any number of channels. (Recommended learning: Redis video tutorial)
Redis provides a publish and subscribe function, which can be used for message transmission. The publish and subscribe mechanism of Redis includes three parts, publisher, Subscribers and Channels.
The publisher and subscriber are both Redis clients, and Channel is the Redis server. The publisher sends the message to a certain channel and subscribes to this Subscribers to the channel will receive this message. Redis's publish and subscribe mechanism is similar to topic-based publish and subscribe, and Channel is equivalent to a topic.
1, introduce Jedis
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
2, specific implementation code
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); } } }
For more Redis related technical articles, please visit Redis database usage introductory tutorial column to learn!
The above is the detailed content of What is the use of redis publish and subscribe?. For more information, please follow other related articles on the PHP Chinese website!