Redis也可以用作队列,其支持队列特性的功能就是发布订阅,但是如果业务上真的用到了队列。还是用一些队列产品吧。毕竟“术业有专攻”(呵,文邹邹的)。
1.Redis命令方式
subscribe
话题名称1
话题名称2
-
2.Redission使用Topic
Redission使用Topic也比较简单。
注册Topic监听
RTopic topic = redissonClient.getTopic(PubAndSubTest.TOPIC);
topic.addListener(String.class, new MessageListener<String>() {
@Override
public void onMessage(CharSequence charSequence, String s) {
System.out.println("订阅的话题名称: " + charSequence);
System.out.println("消息内容:" + s);
}
});
发送消息到Topic
@GetMapping("testPublish")
public String testPublish(String msg){
RTopic topic = redissonClient.getTopic(TOPIC);
topic.publish(msg);
return "ok";
}
接收对象
```java // 接收对象消息 RTopic topic1 = redissonClient.getTopic(PubAndSubTest.TOPIC1); topic1.addListener(User.class, new MessageListener
() { @Override
public void onMessage(CharSequence charSequence, User msg) {
System.out.println("订阅的话题名称: " + charSequence);
System.out.println("消息内容:" + msg);
}
});
// 发送 @PostMapping(“testPublish1”) public String testPublish1(@RequestBody User msg){ RTopic topic = redissonClient.getTopic(TOPIC1); topic.publish(msg); return “ok”; }
<a name="oRbqr"></a>
## 模糊订阅
```java
// 订阅所有满足`topic1.*`表达式的话题
RPatternTopic topic2 = redissonClient.getPatternTopic("boot-redission*");
topic2.addListener(String.class, new PatternMessageListener<String>() {
@Override
public void onMessage(CharSequence pattern, CharSequence topicName, String message) {
System.out.println("reg表达式:"+pattern);
System.out.println("话题名称:"+topicName);
System.out.println("消息:"+message);
}
});
参考资料
https://github.com/redisson/redisson/wiki/6.-%E5%88%86%E5%B8%83%E5%BC%8F%E5%AF%B9%E8%B1%A1