redis发布订阅策略

背景

多个客户端client1、client2、client3订阅redis服务,当redis服务有修改时,将修改内容发布至订阅的客户端。

实现方案

1.定义实现抽象类JedisPubSub的RedisMsgPubSubListener

Jedis定义了抽象类JedisPubSub,在这个类中,定义publish/subsribe的回调方法。通过继承JedisPubSub类并重新实现这些回调方法,当publish/subsribe事件发生时,我们可以定制自己的处理逻辑。

public class RedisMsgPubSubListener extends JedisPubSub {    
public RedisMsgPubSubListener() {        super();    }    
@Override    
public void unsubscribe() {        super.unsubscribe();    }    
@Override    
public void unsubscribe(String... channels) {        super.unsubscribe(channels);    }    
@Override    
public void subscribe(String... channels) {        super.subscribe(channels);    }    
@Override    
public void psubscribe(String... patterns) {        super.psubscribe(patterns);    }    
@Override    
public void punsubscribe() {        super.punsubscribe();    }    
@Override    
public void punsubscribe(String... patterns) {        super.punsubscribe(patterns);    }    
@Override    
public boolean isSubscribed() {        return super.isSubscribed();    }    
@Override    
public void proceedWithPatterns(Client client, String... patterns) {        super.proceedWithPatterns(client, patterns);    }    
@Override    
public void proceed(Client client, String... channels) {        super.proceed(client, channels);    }    
@Override    
public int getSubscribedChannels() {        return super.getSubscribedChannels();    }    
@Override   
 public void onMessage(String channel, String message) {        System.out.println("channel:" + channel + "receives message :" + message);        //this.unsubscribe();    }    
@Override    
public void onPMessage(String pattern, String channel, String message) {    }    
@Override    
public void onSubscribe(String channel, int subscribedChannels) {        System.out.println("channel:" + channel + "is been subscribed:" + subscribedChannels);    }    
@Override    
public void onUnsubscribe(String channel, int subscribedChannels) {        System.out.println("channel:" + channel + "is been unsubscribed:" + subscribedChannels);    }   
@Override    
public void onPUnsubscribe(String pattern, int subscribedChannels) {    }    
@Override    
public void onPSubscribe(String pattern, int subscribedChannels) {    }}

单元测试

订阅测试

@Testpublic void sub1Test(){    
Jedis jedis = new Jedis("localhost");    
RedisMsgPubSubListener listener = new RedisMsgPubSubListener();    
listener.subscribe("redisChatTest");   
 jedis.subscribe(listener, "redisChatTest");
}

发布测试

@Test
public void pubTest() throws Exception{    
Jedis jedis = new Jedis("localhost");    
jedis.publish("redisChatTest", "我是天才");   
 jedis.publish("redisChatTest", "我牛逼");    
jedis.publish("redisChatTest", "哈哈");
}

输出结果

redis发布订阅策略_第1张图片
输出结果.png

你可能感兴趣的:(redis发布订阅策略)