答案:基于Swoole的异步长连接特性,通过自定义JSON协议实现RPC服务,包含服务注册、序列化、通信解包与远程调用;服务端监听请求并解析执行,客户端发送带长度头的请求数据并接收响应,支持协程并发调用,可扩展超时、加密等机制。
Swoole 实现一个简单的 RPC 服务,核心是利用其异步、长连接的特性,通过自定义协议在客户端和服务端之间传递方法调用信息。整个流程包括服务注册、数据序列化、网络通信和远程方法执行。下面分步骤说明如何用 Swoole 快速搭建一个基础的 RPC 框架。
1. 设计基本通信协议
RPC 的关键是定义清晰的请求与响应格式。我们可以使用简单的 JSON 协议来传输调用信息:
请求数据结构示例:
- method:要调用的方法名
- params:参数数组
- id:请求唯一标识(用于回调匹配)
响应数据结构示例:
- id:对应请求的 id
- result:执行结果
- error:错误信息(无错为 null)
数据发送前需拼接长度头,解决 TCP 粘包问题。比如先发送 4 字节的包长度,再发送实际内容。
2. 编写 RPC 服务端
使用 SwooleServer 创建 TCP 服务,监听调用请求:
$server = new SwooleServer('127.0.0.1', 9502); // 模拟提供的服务类 class UserService { public function getUser($id) { return ['id' => $id, 'name' => 'Alice']; } } $services = [ 'UserService' => new UserService(), ]; $server->on('Receive', function ($serv, $fd, $reactorId, $data) use ($services) { // 解包:先读取头部长度,再读取完整 JSON 数据 $length = unpack('N', substr($data, 0, 4))[1]; $json = substr($data, 4, $length); $request = json_decode($json, true); $serviceMethod = explode('.', $request['method']); // 格式:ServiceName.methodName $serviceName = $serviceMethod[0]; $methodName = $serviceMethod[1]; $result = null; $error = null; try { if (!isset($services[$serviceName])) { throw new Exception("Service not found"); } $service = $services[$serviceName]; if (!method_exists($service, $methodName)) { throw new Exception("Method not found"); } $result = call_user_func_array([$service, $methodName], $request['params']); } catch (Exception $e) { $error = $e->getMessage(); } // 构造响应 $response = json_encode([ 'id' => $request['id'], 'result' => $result, 'error' => $error, ]); $sendData = pack('N', strlen($response)) . $response; $serv->send($fd, $sendData); }); $server->start();
3. 编写 RPC 客户端
客户端通过 SwooleCoroutineSocket 或同步 Socket 连接服务端并发送请求:
function rpcCall($method, $params) { $client = new SwooleCoroutineClient(SWOOLE_SOCK_TCP); if (!$client->connect('127.0.0.1', 9502, 0.5)) { throw new Exception("Connect failed"); } $request = json_encode([ 'id' => uniqid(), 'method' => $method, 'params' => $params, ]); $data = pack('N', strlen($request)) . $request; $client->send($data); // 先读 4 字节长度 $head = $client->recv(4); $bodyLength = unpack('N', $head)[1]; $response = $client->recv($bodyLength); $result = json_decode($response, true); $client->close(); if ($result['error']) { throw new Exception($result['error']); } return $result['result']; }
调用示例:
“`php try { $user = rpcCall(‘UserService.getUser’, [1001]); var_dump($user); // 输出: [‘id’ => 1001, ‘name’ => ‘Alice’] } catch (Exception $e) { echo “RPC Error: ” . $e->getMessage(); } “`
4. 支持协程并发调用
Swoole 的优势在于协程并发。可以同时发起多个 RPC 请求,提升效率:
go(function () { $ch1 = chan(); $ch2 = chan(); go(function () use ($ch1) { $ch1->push(rpcCall('UserService.getUser', [1])); }); go(function () use ($ch2) { $ch2->push(rpcCall('UserService.getUser', [2])); }); $user1 = $ch1->pop(); $user2 = $ch2->pop(); var_dump($user1, $user2); });
基本上就这些。一个轻量级的 Swoole RPC 服务就跑起来了。重点是协议设计、解包处理和异常控制。后续可扩展服务发现、超时机制、加密序列化等。不复杂但容易忽略细节。
以上就是Swoole如何实现一个简单的RPC服务的详细内容,更多请关注php react js json go 字节 ai swoole php swoole json echo NULL try catch Error 数据结构 参数数组 并发 异步 rpc