2 Star 0 Fork 0

LeoYang / EventBus

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

A lightweight event bus that implements publish-subscribe based on C++17.

基于C++17实现发布订阅的轻量级事件总线。

事件总线

特点

  • 用来简化线程间/组件间通信与数据传输,代替Event、Message和Callback Function等
  • 基于发布/订阅模式,分离了事件的发送者和接收者,实现业务代码的解耦
  • 通过懒汉式线程安全的单例调用发布订阅函数
  • 超级轻量的实现,只有一个头(.h)文件和一个实现(.cpp)文件
  • 发布订阅函数是线程安全的

示例

1.定义一个结构体

struct person
{
	std::string name;
	std::uint16_t age;
	std::string telephone_number;
};

2.定义一个消息令牌

const std::string send_person_token = "send_person_token";

3.实现消息发布

/// <summary>
/// 获取事件总线默认实例。
/// </summary>
event_bus& bus = event_bus::get_default();

/// <summary>
/// 发布消息。
/// </summary>
void publisher::publish_message() const
{
	person p;
	std::vector<person> p_vector;
	p_vector.reserve(100000);
	for (size_t i = 0; i < 1000; i++)
	{
		p.name = "xiao li zi";
		p.age = 99;
		p.telephone_number = "19911110000";
		p_vector.push_back(std::move(p));
	}

	bus.publish(send_person_token, p_vector);
}

4.实现消息订阅

auto subscribe_message = [&](const std::vector<person>& p_vector)
{
    const auto p = p_vector.back();
    const string str = string_format("%s   name:%s   age:%d   telephone_number:%s", get_current_datetime_string().c_str(),
                                     p.name.c_str(), p.age, p.telephone_number.c_str());
    cout << str << endl;
};

bus.subscribe<std::vector<person>>(send_person_token, subscribe_message);

Licence

该项目根据MIT许可证授权

MIT License Copyright (c) 2020 Leo Yang Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

A lightweight event bus that implements publish-subscribe based on C++17. 展开 收起
C++
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
C++
1
https://gitee.com/LeoYang-Chuese/EventBus.git
git@gitee.com:LeoYang-Chuese/EventBus.git
LeoYang-Chuese
EventBus
EventBus
master

搜索帮助