Redis: Jedis中publish/subscribe 使用

来源:互联网 发布:慕课网 yii2 商城源码 编辑:程序博客网 时间:2024/06/05 22:34

 

 

在Redis早期版本就已经提供publish/subscribe 模式,该文使用Jedis客户端的一个小例子.

 

Jedis 类中提供:

在Jedis中提供 发布二进制编码 ,string字符串 以及pattern匹配模式三种方式来发布publish消息.

 

public Long publish(final String channel, final String message);

public Long publish(byte[] channel, byte[] message);

public List<String> pubsubChannels(String pattern) ;

 

同时提供 二进制编码和string字符串来订阅消息.

public void subscribe(BinaryJedisPubSub jedisPubSub, byte[]... channels)

public void subscribe(final JedisPubSub jedisPubSub, final String... channels)

 

在订阅消息中涉及到2个重要类.BinaryJedisPubSub 和JedisPubSub 类,这2个类用来处理收到消息时,对消息的逻辑处理.

public abstract class JedisPubSub {

}

public abstract class BinaryJedisPubSub {

}

这两个类为抽象类必须通过用户来实现该类. 这两个类中分别有重要的方法onMessage 当收到消息时需要处理.

public void onMessage(byte[] channel, byte[] message) {
  }

  public void onMessage(String channel, String message) {
  }

 

 

PublishMsg.java  发布消息端:

 

    Jedis jedis = new Jedis("localhost");    //发布Protocol Buffer 协议消息        Builder builder = UserBean.newBuilder();    builder.setId(1000);    UserBean userbean = builder.build();    ByteArrayOutputStream output =new ByteArrayOutputStream();    userbean.writeTo(output);    long loop=0;while (loop++<10000) {//发布userbean 二进制消息jedis.publish("userbean".getBytes(), output.toByteArray());Thread.sleep(1000);}     jedis.disconnect();


SubscribeMsg.java 订阅消息端:

    Jedis jedis = new Jedis("localhost");            //业务逻辑处理    UserBeanListener l =new UserBeanListener();    //订阅userbean二进制消息    jedis.subscribe(l, "userbean".getBytes());    long loop=0;while (loop++<10000){Thread.sleep(1000);}     jedis.disconnect();


UserBeanListener.java 业务消息处理:

public class UserBeanListener extends BinaryJedisPubSub {@Overridepublic void onMessage(byte[] channel, byte[] message) {try {UserBean u = UserBean.parseFrom(message);System.out.println(u.getId());} catch (InvalidProtocolBufferException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


UserMsg.proto  ProtocolBuffer协议文件:

message UserBean{// ID(必需)required int32 id = 1;}


 

 

 

 

 

 

 

0 0
原创粉丝点击