Files
docsify-jsonrpc/zh-cn/service_splitting.md
2025-07-17 11:52:59 +08:00

123 lines
3.5 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.

# 服务拆分
> 项目拆分为 **公共服务** 和 **对外接口服务**:主要逻辑提供对外接口服务,公共服务提供基础服务(如微信接口服务、权限服务、用户服务等)。
### 为什么要拆分?
1. **提高可维护性**:拆分为较小服务(公共服务、对外接口服务等)使代码库清晰易管理,每个服务职责明确,减少复杂度,便于维护和更新。
2. **增强扩展性**:服务可独立扩容,例如微信接口服务负载增加时可单独扩容,而不影响其他服务。
3. **简化部署过程**:小型服务更易于部署,可更快发布新功能和修复 bug降低整体风险。
4. **提升容错能力**:服务隔离,一个服务出错不会轻易影响其他服务。
5. **促进团队协作**:不同团队/成员可专注于不同服务并行开发,效率更高,也可选择最合适的技术栈。
6. **优化资源利用**按服务需求分配资源CPU/内存),提高资源利用率,降低成本。
---
## 整体架构图
> 使用时序图直观展示服务拆分与通信关系:
```mermaid
sequenceDiagram
participant Client as HTTP API 接口
participant User as 用户服务
participant Perm as 权限服务
participant WeChat as 微信服务
participant Nacos as 注册中心
Client->>User: JSON-RPC 请求
Client->>Perm: JSON-RPC 请求
Client->>WeChat: JSON-RPC 请求
loop 服务注册/发现
User->>Nacos: 注册/发现
Perm->>Nacos: 注册/发现
WeChat->>Nacos: 注册/发现
end
Note right of Nacos: 管理服务注册<br/>和健康检查
User-->>Client: 返回用户数据
Perm-->>Client: 返回权限数据
WeChat-->>Client: 返回微信数据
```
---
## 核心组件说明
| 组件 | 作用 |
|------|------|
| **Nacos** | 服务注册与发现中心,管理服务实例和健康检查 |
| **JSON-RPC** | 轻量级服务间通信协议,结构清晰,跨语言调用友好 |
| **Hyperf** | 高性能协程框架,提供 RPC 客户端/服务端及服务治理能力 |
---
## 实现步骤详解
### 1⃣ 安装依赖
```bash
composer require hyperf/json-rpc
composer require hyperf/rpc-server
```
---
### 2⃣ 启动 Nacos 服务注册中心
可使用 Docker 快速启动:
```bash
docker run -d -p 8848:8848 --name nacos nacos/nacos-server
# 访问 http://localhost:8848/nacos 查看服务注册情况
```
---
### 3⃣ 创建服务提供者
#### 定义接口Interface
```php
// app/Service/UserServiceInterface.php
namespace App\Service;
interface UserServiceInterface
{
public function getUserById(int $id): array;
}
```
#### 实现接口逻辑
```php
// app/Service/Impl/UserServiceImpl.php
namespace App\Service\Impl;
use App\Service\UserServiceInterface;
class UserServiceImpl implements UserServiceInterface
{
public function getUserById(int $id): array
{
// 模拟数据库查询
return ['id' => $id, 'name' => '张三'];
}
}
```
---
## 服务注册与发现流程
1. 公共服务启动后,通过 **JsonRpcServer** 在指定端口监听;
2. 并向 **Nacos** 注册服务名(如 `App\Service\UserServiceInterface`)和地址;
3. 对外接口服务启动后,从 **Nacos** 获取所需服务地址;
4. 通过 Hyperf 内置 **JSON-RPC 客户端** 调用远程方法;
5. 调用过程自动完成 JSON-RPC 协议序列化/反序列化;
6. 内置支持负载均衡(随机、轮询等)和容错(失败重试、熔断等)。
---