本文主要是介绍Redis: Jedis 源代码剖析2- 发布者/订阅者模式剖析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在Jedis提供的发布者/订阅者模式中,最重要的就是JedisPubSub . 当订阅通道后,JedisPubSub就会轮询通道。直到通道取消订阅,才会继续执行。
因为Jedis是单线程,所以当订阅之后,线程就在循环。除非,在JedisPubSub收到消息后,新开线程继续执行任务。
在JedisPubSub 类中定义了接受消息后触发事件和轮询代码。JedisPubSub类是抽象类,所以为了实现自己的功能,必须继承该类。
public abstract class JedisPubSub {private int subscribedChannels = 0;private volatile Client client;public void onMessage(String channel, String message) {}public void onPMessage(String pattern, String channel, String message) {}public void onSubscribe(String channel, int subscribedChannels) {}public void onUnsubscribe(String channel, int subscribedChannels) {}public void onPUnsubscribe(String pattern, int subscribedChannels) {}public void onPSubscribe(String pattern, int subscribedChannels) {}public void unsubscribe() {if (client == null) {throw new JedisConnectionException("JedisPubSub was not subscribed to a Jedis instance.");}client.unsubscribe();client.flush();}public void unsubscribe(String... channels) {if (client == null) {throw new JedisConnectionException("JedisPubSub is not subscribed to a Jedis instance.");}client.unsubscribe(channels);client.flush();}public void subscribe(String... channels) {if (client == null) {throw new JedisConnectionException("JedisPubSub is not subscribed to a Jedis instance.");}client.subscribe(channels);client.flush();}public void psubscribe(String... patterns) {if (client == null) {throw new JedisConnectionException("JedisPubSub is not subscribed to a Jedis insta
这篇关于Redis: Jedis 源代码剖析2- 发布者/订阅者模式剖析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!