z-docs/docs/tutorial-basics/publish-subscribe.md
2024-04-21 12:38:27 +08:00

42 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
sidebar_position: 1
title: 订阅&发布
description: zhub 创建客户端连接、订阅主题、发送主题消息
---
:::tip
发布-订阅Publish-Subscribe消息中间件可以用于实现发布-订阅模式。发布者将消息发布到一个或多个主题Topic而订阅者订阅感兴趣的主题。当有新的消息发布到主题时所有订阅了该主题的订阅者都会接收到消息。这样可以实现一对多的消息传递降低发送方和接收方之间的耦合性。
首先完成 **[连接创建](create-connection.md)** ,便可进行消息的发送和接收,
- [订阅主题消息](#订阅主题消息)
- [发送主题消息](#发送主题消息)
:::
## 订阅主题消息
```java
// 事件订阅
zhub.subscribe("topic-a", x -> {
System.out.println("接收到主题 topic-a 事件,消息内容:" + x);
});
```
## 发送主题消息
测试发送主题消息
```java
private ZHubClient zhub;
@RestMapping(name = "publish_test", auth = false, comment = "发送主题消息测试")
public String publishTest(String value) {
zhub.publish("topic-a", value);
return "send ok!";
}
```
这个时候,将会在订阅端收到主题订阅消息,并在控制台输出: `接收到主题 topic-a 事件消息内容xx` 的消息内容