hyperf实现简单的rpc服务(win10 + docker+consul)

拉取docker镜像

docker run --name codes \
-v E:/project/www:/home/www \
-p 9501:9501 \
-p 9502:9502 -it \
--privileged -u root \
--entrypoint /bin/sh \
hyperf/hyperf:7.4-alpine-v3.11-swoole

安装 consul
docker pull consul
docker run --name=consul -p 8500:8500 -e CONSUL_BIND_INTERFACE=eth0 -d consul
访问consul
http://127.0.0.1:8500/

image.png

创建服务提供者项目(服务端)
composer create-project hyperf/hyperf-skeleton server-provider
切换阿里云镜像源
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer
安装组件
composer require hyperf/json-rpc
composer require hyperf/rpc-server
composer require hyperf/rpc-client
composer require hyperf/service-governance
composer require hyperf/service-governance-consul
composer require hyperf/consul
发布组件(生成 autoload/services.php文件)
php bin/hyperf.php vendor:publish hyperf/service-governance
编写服务提供者接口

<?php
declare(strict_types=1);
namespace App\JsonRpc;
interface CalculatorServiceInterface {
    public function list();
}

接口实现

<?php
namespace App\JsonRpc;
use Hyperf\RpcServer\Annotation\RpcService;
/**
 * 服务提供者
 * 注意,如希望通过服务中心来管理服务,需在注解内增加 publishTo 属性
 * @RpcService(name="CalculatorService", protocol="jsonrpc", server="jsonrpc",publishTo="consul")
 */
class CalculatorService implements CalculatorServiceInterface
{
    protected $list = [
        ['id'=>1, 'name'=>'Mr.Li', 'age' => 20],
        ['id'=>2, 'name'=>'Mr.Zhang', 'age' => 30]
    ];

    public function list()
    {
        return $this->list;
    }
}

server.php配置


image.png

services.php配置(通过发布生成 php bin/hyperf vendor:publish hyperf/service-governance

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
return [
    'enable' => [
        'discovery' => true,
        'register' => true,
    ],
    'consumers' => [
        [
            // The service name, this name should as same as with the name of service provider.
            'name' => 'CalculatorService',
            // The service registry, if `nodes` is missing below, then you should provide this configs.
            // 服务接口名,可选,默认值等于 name 配置的值,如果 name 直接定义为接口类则可忽略此行配置,如 name 为字符串则需要配置 service 对应到接口类
            'service' => \App\JsonRpc\CalculatorServiceInterface::class,
            // 服务提供者的服务协议,可选,默认值为 jsonrpc-http
            'protocol' => 'jsonrpc',
            // 负载均衡算法,可选,默认值为 random
            'load_balancer' => 'random',
            // 对应容器对象 ID,可选,默认值等于 service 配置的值,用来定义依赖注入的 key
            'id' => \App\JsonRpc\CalculatorServiceInterface::class,
            // If `registry` is missing, then you should provide the nodes configs.
            'nodes' => [
                // Provide the host and port of the service provider.
                ['host' => '127.0.0.1', 'port' => 9503]
            ],
            // 配置项,会影响到 Packer 和 Transporter
            'options' => [
                'connect_timeout' => 5.0,
                'recv_timeout' => 5.0,
                'settings' => [
                    // 根据协议不同,区分配置
                    'open_eof_split' => true,
                    'package_eof' => "\r\n",
                    // 'open_length_check' => true,
                    // 'package_length_type' => 'N',
                    // 'package_length_offset' => 0,
                    // 'package_body_offset' => 4,
                ],
                // 当使用 JsonRpcPoolTransporter 时会用到以下配置
                'pool' => [
                    'min_connections' => 1,
                    'max_connections' => 32,
                    'connect_timeout' => 10.0,
                    'wait_timeout' => 3.0,
                    'heartbeat' => -1,
                    'max_idle_time' => 60.0,
                ],
            ]

        ],
    ],
    'providers' => [],
    'drivers' => [
        'consul' => [
            'uri' => 'http://172.17.0.2:8500',
            'token' => '',
            'check' => [
                'deregister_critical_service_after' => '90m',
                'interval' => '1s',
            ],
        ]
    ],
];

服务端配置完成



创建服务箱费者项目(客户端)
composer create-project hyperf/hyperf-skeleton server-consumer

消费者接口(和服务端接口一样,不用去写这个接口的实现类,当我们通过访问这个接口的时候,请求会自动根据配置在服务中心去找询这个接口的实现类,并调用)

<?php
declare(strict_types=1);
namespace App\JsonRpc;
interface CalculatorServiceInterface {
    public function list();
}

消费者配置文件server.php配置

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
use Hyperf\Server\Event;
use Hyperf\Server\Server;
use Swoole\Constant;

return [
    'mode' => SWOOLE_PROCESS,
    'servers' => [
        [
            'name' => 'http',
            'type' => Server::SERVER_HTTP,
            'host' => '0.0.0.0',
            'port' => 9601,
            'sock_type' => SWOOLE_SOCK_TCP,
            'callbacks' => [
                Event::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'],
            ],
        ],
        [
            //  这里和服务端的name是一样的
            'name' => 'jsonrpc',
            'type' => Server::SERVER_BASE,
            'host' => '0.0.0.0',
            'port' => 9603,
            'sock_type' => SWOOLE_SOCK_TCP,
            'callbacks' => [
                Event::ON_RECEIVE => [\Hyperf\JsonRpc\TcpServer::class, 'onReceive'],
            ],
            'settings' => [
                'open_eof_split' => true,
                'package_eof' => "\r\n",
                'package_max_length' => 1024 * 1024 * 2,
            ],
        ]
    ],
    'settings' => [
        Constant::OPTION_ENABLE_COROUTINE => true,
        Constant::OPTION_WORKER_NUM => swoole_cpu_num(),
        Constant::OPTION_PID_FILE => BASE_PATH . '/runtime/hyperf.pid',
        Constant::OPTION_OPEN_TCP_NODELAY => true,
        Constant::OPTION_MAX_COROUTINE => 100000,
        Constant::OPTION_OPEN_HTTP2_PROTOCOL => true,
        Constant::OPTION_MAX_REQUEST => 100000,
        Constant::OPTION_SOCKET_BUFFER_SIZE => 2 * 1024 * 1024,
        Constant::OPTION_BUFFER_OUTPUT_SIZE => 2 * 1024 * 1024,
    ],
    'callbacks' => [
        Event::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'],
        Event::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'],
        Event::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'],
    ],
];

消费者配置文件services.php配置

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

return [
    'enable' => [
        'discovery' => true,
        'register' => true,
    ],
    'consumers' =>  [
        // jsonrpc 通过consul中台进行请求
        [
            'name'  =>  'CalculatorService',
            'service'   =>  \App\JsonRpc\CalculatorServiceInterface::class,
            'protocol'  =>  'jsonrpc', // 默认为jsonrpc-http 所需必须进行指定
            'registry' => [
                'protocol' => 'consul',
                'address' => 'http://172.17.0.2:8500', // 这里需要自己的consul地址,我这里是docker容器内部的id
            ],
        ],
    ],
    'providers' => [],
    'drivers' => [
        'consul' => [
            'uri' => 'http://172.17.0.2:8500',
            'token' => '',
            'check' => [
                'deregister_critical_service_after' => '90m',
                'interval' => '1s',
            ],
        ],
        //  使用nacos为服务注册中心的时候配置
        'nacos' => [
            // nacos server url like https://nacos.hyperf.io, Priority is higher than host:port
            // 'url' => '',
            // The nacos host info
            'host' => '127.0.0.1',
            'port' => 8848,
            // The nacos account info
            'username' => null,
            'password' => null,
            'guzzle' => [
                'config' => null,
            ],
            'group_name' => 'api',
            'namespace_id' => 'namespace_id',
            'heartbeat' => 5,
            'ephemeral' => false,
        ],
    ],
];


启动服务端,服务将会自动推送到consul


image.png

consul.png

启动客户端(消费者)


image.png

在消费者端编写测试文件

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller;

use App\JsonRpc\CalculatorServiceInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\RpcClient\Client;
use Hyperf\Utils\ApplicationContext;

/**
 * @AutoController()
 */
class IndexController extends AbstractController
{
    /**
     * @Inject()
     * @var CalculatorServiceInterface
     */
    protected $calculator;

    public function rpc(): array
    {
        $res = $this->calculator->list();
        return ['res' => $res, 'time' => date('Y-m-d H:i:s',time())];
    }
}

访问接口 http://127.0.0.1:9601/index/rpc
返回结果

image.png

end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容