# Json-Rpc **Repository Path**: box-he-he/json-rpc ## Basic Information - **Project Name**: Json-Rpc - **Description**: 基于C++实现的Json-Rpc框架 - **Primary Language**: C++ - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2024-12-04 - **Last Updated**: 2025-03-02 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Json-RPC 框架 一个基于 `C++` 实现的高性能 `RPC` 框架,支持服务注册发现、同步/异步调用、发布订阅等功能。 ## 功能特性 - 基于 `muduo` 网络库实现高性能网络通信 - 使用 `JSON` 作为序列化格式 - 基于 `future` 支持同步、异步、回调三种调用方式 - 支持服务注册与发现 - 支持发布订阅模式 - 线程安全设计 - 完善的错误处理机制 ## 系统架构 总框架: ![otalFram](img/totalFrame.png) ### 1. 网络通信层 - 基于 muduo 实现 TCP 长连接 - 自定义消息协议格式: `| length | mtype | idlength | id | body |` - 支持消息分片处理 - 异步事件驱动模型 通信格式: ![VProtoco](img/LVProtocol.png) 网络层架构: ![e](img/net.png) ### 2. RPC 调用模块 #### 2.1 请求管理 (Requestor) - 使用 UUID 标识每个请求 - 维护请求-响应映射关系 - 支持请求超时处理 - 支持请求并发控制 #### 2.2 调用方式 - 同步调用:等待响应返回 - 异步调用:基于 std::future 实现 - 回调方式:注册回调函数处理响应 ### 3. 服务注册发现 #### 3.1 注册中心服务器 (RegistryServer) - 管理服务提供方信息 - 处理服务注册请求 - 处理服务发现请求 - 服务上下线通知 - 服务负载均衡 #### 3.2 服务管理 (PDManager) - ProviderManager:管理服务提供方 - DiscoverManager:管理服务发现方 - 支持服务动态上下线 服务发现端: ![pc_registry_clien](img/rpc_registry_client.png) 服务提供端: ![pc_registry_serve](img/rpc_registry_server.png) ### 4. 发布订阅系统 #### 4.1 主题管理 (TopicManager) - 支持主题的创建与删除 - 管理订阅关系 - 消息推送分发 #### 4.2 订阅者管理 - 支持多订阅者 - 支持动态订阅/取消 - 处理订阅者异常下线 主题服务端: ![opic_serve](img/topic_server.png) 主题订阅端: ![opic_clien](img/topic_client.png) ## 核心类说明 ### 基础类 - BaseMessage: 消息基类![essag](img/Message.png) - BaseBuffer: 缓冲区基类 - BaseProtocol: 协议基类 - BaseConnection: 连接基类 - BaseServer/BaseClient: 服务端/客户端基类 ### 服务端类 - RpcServer: RPC 服务提供方 - RegistryServer: 注册中心服务器 - TopicServer: 主题订阅服务器 - ServiceDescriber: 服务描述类 - RpcRouter: 服务路由管理 ### 客户端类 - RpcClient: RPC 服务调用方 - RegistryClient: 服务注册客户端 - DiscoverClient: 服务发现客户端 - TopicClient: 主题订阅客户端 ## 使用示例 ### 启动注册中心 ```cpp RegistryServer server(8000); server.start(); ``` ### 启动 RPC 服务端 ```cpp Address addr("127.0.0.1", 8001); RpcServer server(addr, true, Address("127.0.0.1", 8000)); server.registerMethod(service); server.start(); ``` ### RPC 客户端调用 ```cpp // 同步调用 RpcClient client(true, "127.0.0.1", 8000); Json::Value result; client.call("method", params, result); // 异步调用 RpcCaller::JsonAsyncResponse future; client.call("method", params, future); result = future.get(); // 回调方式 client.call("method", params, [](Json::Value result) { // 处理结果 }); ``` ### 发布订阅使用 ```cpp // 订阅者 TopicClient client("127.0.0.1", 8002); client.subscribeTopic("topic1", [](const std::string& msg) { // 处理消息 }); // 发布者 TopicClient client("127.0.0.1", 8002); client.publishTopic("topic1", "hello world"); ``` ## 编译运行 ### 依赖 - muduo 网络库 - jsoncpp - C++11 或更高版本 ### 编译 ```bash make all ``` ## 注意事项 1. 需要先启动注册中心,再启动服务提供方 2. 使用服务发现功能时需要配置正确的注册中心地址 3. 注意处理网络异常和超时情况 4. 建议在服务端实现中注意线程安全