1. Redis也可以用作队列,其支持队列特性的功能就是发布订阅,但是如果业务上真的用到了队列。还是用一些队列产品吧。毕竟“术业有专攻”(呵,文邹邹的)。

1.Redis命令方式

  • subscribe 话题名称1 话题名称2
  • publish 话题名称 消息

    2.Redission使用Topic

    Redission使用Topic也比较简单。

  • 注册Topic监听

    1. RTopic topic = redissonClient.getTopic(PubAndSubTest.TOPIC);
    2. topic.addListener(String.class, new MessageListener<String>() {
    3. @Override
    4. public void onMessage(CharSequence charSequence, String s) {
    5. System.out.println("订阅的话题名称: " + charSequence);
    6. System.out.println("消息内容:" + s);
    7. }
    8. });
  • 发送消息到Topic

    1. @GetMapping("testPublish")
    2. public String testPublish(String msg){
    3. RTopic topic = redissonClient.getTopic(TOPIC);
    4. topic.publish(msg);
    5. return "ok";
    6. }

    接收对象

    ```java // 接收对象消息 RTopic topic1 = redissonClient.getTopic(PubAndSubTest.TOPIC1); topic1.addListener(User.class, new MessageListener() {

    1. @Override
    2. public void onMessage(CharSequence charSequence, User msg) {
    3. System.out.println("订阅的话题名称: " + charSequence);
    4. System.out.println("消息内容:" + msg);
    5. }

    });

// 发送 @PostMapping(“testPublish1”) public String testPublish1(@RequestBody User msg){ RTopic topic = redissonClient.getTopic(TOPIC1); topic.publish(msg); return “ok”; }

  1. <a name="oRbqr"></a>
  2. ## 模糊订阅
  3. ```java
  4. // 订阅所有满足`topic1.*`表达式的话题
  5. RPatternTopic topic2 = redissonClient.getPatternTopic("boot-redission*");
  6. topic2.addListener(String.class, new PatternMessageListener<String>() {
  7. @Override
  8. public void onMessage(CharSequence pattern, CharSequence topicName, String message) {
  9. System.out.println("reg表达式:"+pattern);
  10. System.out.println("话题名称:"+topicName);
  11. System.out.println("消息:"+message);
  12. }
  13. });

参考资料

https://github.com/redisson/redisson/wiki/6.-%E5%88%86%E5%B8%83%E5%BC%8F%E5%AF%B9%E8%B1%A1