举一个实际代码例子,分订阅代码和发布代码
时间: 2023-07-09 12:50:33 浏览: 43
好的,假设我们有两个模块 A 和 B,需要通过 Common API C++ 的消息总线进行通信。A 模块需要向 B 模块发送一个消息,B 模块需要监听该消息并进行响应。下面是一个实际的代码例子:
订阅代码(B 模块):
```cpp
#include <CommonAPI/CommonAPI.hpp>
#include <v1/com/example/MyServiceProxy.hpp>
using namespace v1::com::example;
class MyServiceListener : public MyServiceProxy {
public:
MyServiceListener() = default;
void onMessage(const std::string& message) override {
std::cout << "B 模块收到消息:" << message << std::endl;
// TODO: 处理消息
}
};
int main() {
std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get();
std::shared_ptr<MyServiceListener> listener = std::make_shared<MyServiceListener>();
runtime->start();
std::shared_ptr<MyServiceProxy> proxy = runtime->buildProxy<MyServiceProxy>("local", "MyService");
proxy->getMessageEvent().subscribe(listener);
std::this_thread::sleep_for(std::chrono::seconds(30)); // 等待消息到达
runtime->stop();
return EXIT_SUCCESS;
}
```
发布代码(A 模块):
```cpp
#include <CommonAPI/CommonAPI.hpp>
#include <v1/com/example/MyServiceStubDefault.hpp>
using namespace v1::com::example;
int main() {
std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get();
std::shared_ptr<MyServiceStubDefault> service = std::make_shared<MyServiceStubDefault>();
runtime->start();
runtime->registerService("local", "MyService", service);
std::shared_ptr<MyServiceProxy> proxy = runtime->buildProxy<MyServiceProxy>("local", "MyService");
proxy->sendMessage("Hello, World!"); // 向 B 模块发送消息
runtime->stop();
return EXIT_SUCCESS;
}
```
在上面的代码中,B 模块通过继承 `MyServiceProxy` 类并实现 `onMessage()` 方法来监听名为 `getMessageEvent()` 的消息事件。当 A 模块通过 `proxy->sendMessage("Hello, World!")` 发送消息时,B 模块就会收到该消息并调用 `onMessage()` 方法进行处理。这样就完成了 A、B 两个模块之间的基于消息总线的通信。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)