Server 端
定义服务(示例)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <?php
declare(strict_types=1);
namespace App\JsonRpc;
use Hyperf\RpcServer\Annotation\RpcService;
class TestsService { public function add(int $a, int $b): int { return $a + $b; } }
|
对外提供服务
文件:config\autoload\server.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <?php
declare(strict_types=1);
use Hyperf\Server\Event; use Hyperf\Server\Server; use Swoole\Constant;
return [ 'mode' => SWOOLE_PROCESS, 'servers' => [ [ 'name' => 'jsonrpc-http', 'type' => Server::SERVER_HTTP, 'host' => '0.0.0.0', 'port' => 8001, 'sock_type' => SWOOLE_SOCK_TCP, 'callbacks' => [ Event::ON_REQUEST => [\Hyperf\JsonRpc\HttpServer::class, 'onRequest'], ], ], ], ];
|
Client 端
配置调用端
此处简易版(未使用 Consul)
相关文件:config\autoload\services.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <?php
declare(strict_types=1);
return [ 'consumers' => [ [ 'name' => 'TestsService', 'nodes' => [ ['host' => '127.0.0.1', 'port' => 8001] ], ], ], ];
|
配置消费端(客户端)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <?php
declare(strict_types=1);
namespace App\JsonRpc;
use Hyperf\RpcClient\AbstractServiceClient;
class TestsConsumer extends AbstractServiceClient {
protected $serviceName = 'TestsService';
protected $protocol = 'jsonrpc-http';
public function add(int $a, int $b): int { return $this->__request(__FUNCTION__, compact('a', 'b')); } }
|
调用消费端
1 2 3
| <?php (new TestsConsumer($this->container))->add(1, 2);
|
HTTP 协议:实际的请求信息
请求地址:
请求方式:
请求参数:
1 2 3 4 5 6 7 8 9 10
| { "jsonrpc": "2.0", "method": "\/tests\/add", "params": { "a": 1, "b": 2 }, "id": "617b67ade764a", "context": [] }
|
返回结果:
1 2 3 4 5 6
| { "jsonrpc": "2.0", "id": "617b67ade764a", "result": 3, "context": [] }
|
进阶
- 多路复用:传送门
- 基于 TCP 协议的 JsonRPC
- gRPC
- RequestID:链路跟踪