基于多路复用的 RPC 组件

本组件基于 TCP 协议,多路复用的设计借鉴于 AMQP 组件。

安装

  1. composer require hyperf/rpc-multiplex

Server 配置

修改 config/autoload/server.php 配置文件,以下配置删除了不相干的配置。

settings 设置中,分包规则不允许修改,只可以修改 package_max_length,此配置需要 ServerClient 保持一致。

  1. <?php
  2. declare(strict_types=1);
  3. use Hyperf\Server\Event;
  4. use Hyperf\Server\Server;
  5. return [
  6. 'servers' => [
  7. [
  8. 'name' => 'rpc',
  9. 'type' => Server::SERVER_BASE,
  10. 'host' => '0.0.0.0',
  11. 'port' => 9502,
  12. 'sock_type' => SWOOLE_SOCK_TCP,
  13. 'callbacks' => [
  14. Event::ON_RECEIVE => [Hyperf\RpcMultiplex\TcpServer::class, 'onReceive'],
  15. ],
  16. 'settings' => [
  17. 'open_length_check' => true,
  18. 'package_length_type' => 'N',
  19. 'package_length_offset' => 0,
  20. 'package_body_offset' => 4,
  21. 'package_max_length' => 1024 * 1024 * 2,
  22. ],
  23. ],
  24. ],
  25. ];

创建 RpcService

  1. <?php
  2. namespace App\RPC;
  3. use App\JsonRpc\CalculatorServiceInterface;
  4. use Hyperf\RpcMultiplex\Constant;
  5. use Hyperf\RpcServer\Annotation\RpcService;
  6. /**
  7. * @RpcService(name="CalculatorService", server="rpc", protocol=Constant::PROTOCOL_DEFAULT)
  8. */
  9. class CalculatorService implements CalculatorServiceInterface
  10. {
  11. }

客户端配置

修改 config/autoload/services.php 配置文件

  1. <?php
  2. declare(strict_types=1);
  3. return [
  4. 'consumers' => [
  5. [
  6. 'name' => 'CalculatorService',
  7. 'service' => App\JsonRpc\CalculatorServiceInterface::class,
  8. 'id' => App\JsonRpc\CalculatorServiceInterface::class,
  9. 'protocol' => Hyperf\RpcMultiplex\Constant::PROTOCOL_DEFAULT,
  10. 'load_balancer' => 'random',
  11. // 这个消费者要从哪个服务中心获取节点信息,如不配置则不会从服务中心获取节点信息
  12. 'registry' => [
  13. 'protocol' => 'consul',
  14. 'address' => 'http://127.0.0.1:8500',
  15. ],
  16. 'nodes' => [
  17. ['host' => '127.0.0.1', 'port' => 9502],
  18. ],
  19. 'options' => [
  20. 'connect_timeout' => 5.0,
  21. 'recv_timeout' => 5.0,
  22. 'settings' => [
  23. // 包体最大值,若小于 Server 返回的数据大小,则会抛出异常,故尽量控制包体大小
  24. 'package_max_length' => 1024 * 1024 * 2,
  25. ],
  26. // 重试次数,默认值为 2
  27. 'retry_count' => 2,
  28. // 重试间隔,毫秒
  29. 'retry_interval' => 100,
  30. // 多路复用客户端数量
  31. 'client_count' => 4,
  32. // 心跳间隔 非 numeric 表示不开启心跳
  33. 'heartbeat' => 30,
  34. ],
  35. ],
  36. ],
  37. ];

注册中心

如果需要使用注册中心,则需要手动添加以下监听器

  1. <?php
  2. return [
  3. Hyperf\RpcMultiplex\Listener\RegisterServiceListener::class,
  4. ];