hyperf實(shí)現(xiàn)簡單的rpc服務(wù)(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

創(chuàng)建服務(wù)提供者項(xiàng)目(服務(wù)端)
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
發(fā)布組件(生成 autoload/services.php文件)
php bin/hyperf.php vendor:publish hyperf/service-governance
編寫服務(wù)提供者接口

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

接口實(shí)現(xiàn)

<?php
namespace App\JsonRpc;
use Hyperf\RpcServer\Annotation\RpcService;
/**
 * 服務(wù)提供者
 * 注意,如希望通過服務(wù)中心來管理服務(wù),需在注解內(nèi)增加 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配置(通過發(fā)布生成 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.
            // 服務(wù)接口名,可選,默認(rèn)值等于 name 配置的值,如果 name 直接定義為接口類則可忽略此行配置,如 name 為字符串則需要配置 service 對應(yīng)到接口類
            'service' => \App\JsonRpc\CalculatorServiceInterface::class,
            // 服務(wù)提供者的服務(wù)協(xié)議,可選,默認(rèn)值為 jsonrpc-http
            'protocol' => 'jsonrpc',
            // 負(fù)載均衡算法,可選,默認(rèn)值為 random
            'load_balancer' => 'random',
            // 對應(yīng)容器對象 ID,可選,默認(rèn)值等于 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]
            ],
            // 配置項(xiàng),會影響到 Packer 和 Transporter
            'options' => [
                'connect_timeout' => 5.0,
                'recv_timeout' => 5.0,
                'settings' => [
                    // 根據(jù)協(xié)議不同,區(qū)分配置
                    'open_eof_split' => true,
                    'package_eof' => "\r\n",
                    // 'open_length_check' => true,
                    // 'package_length_type' => 'N',
                    // 'package_length_offset' => 0,
                    // 'package_body_offset' => 4,
                ],
                // 當(dāng)使用 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',
            ],
        ]
    ],
];

服務(wù)端配置完成



創(chuàng)建服務(wù)箱費(fèi)者項(xiàng)目(客戶端)
composer create-project hyperf/hyperf-skeleton server-consumer

消費(fèi)者接口(和服務(wù)端接口一樣,不用去寫這個接口的實(shí)現(xiàn)類,當(dāng)我們通過訪問這個接口的時候,請求會自動根據(jù)配置在服務(wù)中心去找詢這個接口的實(shí)現(xiàn)類,并調(diào)用)

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

消費(fèi)者配置文件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'],
            ],
        ],
        [
            //  這里和服務(wù)端的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'],
    ],
];

消費(fèi)者配置文件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中臺進(jìn)行請求
        [
            'name'  =>  'CalculatorService',
            'service'   =>  \App\JsonRpc\CalculatorServiceInterface::class,
            'protocol'  =>  'jsonrpc', // 默認(rèn)為jsonrpc-http 所需必須進(jìn)行指定
            'registry' => [
                'protocol' => 'consul',
                'address' => 'http://172.17.0.2:8500', // 這里需要自己的consul地址,我這里是docker容器內(nèi)部的id
            ],
        ],
    ],
    'providers' => [],
    'drivers' => [
        'consul' => [
            'uri' => 'http://172.17.0.2:8500',
            'token' => '',
            'check' => [
                'deregister_critical_service_after' => '90m',
                'interval' => '1s',
            ],
        ],
        //  使用nacos為服務(wù)注冊中心的時候配置
        '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,
        ],
    ],
];


啟動服務(wù)端,服務(wù)將會自動推送到consul


image.png

consul.png

啟動客戶端(消費(fèi)者)


image.png

在消費(fèi)者端編寫測試文件

<?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
返回結(jié)果

image.png

end

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容