task_plan_2/include/core/message_bus.hpp

75 lines
2.3 KiB
C++
Raw Permalink 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.

#ifndef BATTLEFIELD_CORE_MESSAGE_BUS_HPP
#define BATTLEFIELD_CORE_MESSAGE_BUS_HPP
#include <string>
#include <functional>
#include <vector>
#include <map>
#include <mutex>
#include <memory>
#include <nlohmann/json.hpp>
namespace battlefield {
/// @brief 消息总线中的消息
struct BusMessage {
std::string topic; ///< 消息主题
std::string sender; ///< 发送者ID
nlohmann::json payload; ///< 消息载荷JSON
std::string timestamp; ///< 时间戳ISO 8601
};
/// @brief 消息处理器类型
using MessageHandler = std::function<void(const BusMessage&)>;
/// @brief 内部消息总线设计文档3.1要求:组件间通过内部消息总线协作)
/// 实现发布-订阅模式,支持模块解耦、异步处理
class MessageBus {
public:
/// @brief 获取单例实例
static MessageBus& Instance();
/// @brief 发布消息到指定主题
/// @param topic 主题
/// @param sender 发送者ID
/// @param payload 消息载荷
void Publish(const std::string& topic, const std::string& sender,
const nlohmann::json& payload);
/// @brief 发布简单字符串消息
void PublishString(const std::string& topic, const std::string& sender,
const std::string& message);
/// @brief 订阅某个主题
/// @param topic 主题
/// @param handler 消息处理器
/// @return 订阅ID用于取消订阅
int Subscribe(const std::string& topic, MessageHandler handler);
/// @brief 取消订阅
/// @param subscriptionId 订阅ID
void Unsubscribe(int subscriptionId);
/// @brief 获取某个主题的订阅者数量
size_t SubscriberCount(const std::string& topic) const;
/// @brief 获取历史消息数
size_t HistoryCount() const { return history_.size(); }
private:
MessageBus() = default;
MessageBus(const MessageBus&) = delete;
MessageBus& operator=(const MessageBus&) = delete;
/// @brief 生成当前时间戳
static std::string GenerateTimestamp();
int nextSubscriptionId_{1};
std::map<int, std::pair<std::string, MessageHandler>> subscriptions_; ///< subscriptionId -> (topic, handler)
std::vector<BusMessage> history_; ///< 消息历史
};
} // namespace battlefield
#endif // BATTLEFIELD_CORE_MESSAGE_BUS_HPP