一潭兽、開發(fā)項目劃分與搭建
JSON RPC 是一種基于 JSON 格式的輕量級的 RPC 協(xié)議標準朋其,易于使用和閱讀王浴。在 Hyperf 里由 hyperf/json-rpc 組件來實現(xiàn),可自定義基于 HTTP 協(xié)議來傳輸令宿,或直接基于 TCP 協(xié)議來傳輸叼耙。
本次我選擇使用基于 TCP 協(xié)議的 jsonrpc 協(xié)議來搭建服務(wù)腕窥。
服務(wù)有兩種角色粒没,一種是 服務(wù)提供者(ServiceProvider),即為其它服務(wù)提供服務(wù)的服務(wù)簇爆,另一種是 服務(wù)消費者(ServiceConsumer)癞松,即依賴其它服務(wù)的服務(wù)爽撒,一個服務(wù)既可能是 服務(wù)提供者(ServiceProvider),同時又是 服務(wù)消費者(ServiceConsumer)响蓉。而兩者直接可以通過 服務(wù)契約 來定義和約束接口的調(diào)用硕勿,在 Hyperf 里,可直接理解為就是一個 接口類(Interface)枫甲,通常來說這個接口類會同時出現(xiàn)在提供者和消費者下源武。
本次我搭建了一個服務(wù)提供者 calculate,為其他服務(wù)提供計算功能想幻;一個消費者粱栖,通過 jsonrpc 協(xié)議調(diào)用 calculate 提供的計算功能。搭建過程如下:
1脏毯、搭建 calculate 服務(wù)提供者
composer create-project hyperf/hyperf-skeleton calculate
Which RPC protocol do you want to use ?
[1] JSON-RPC with Service Governance
[2] JSON-RPC
[3] gRPC
[n] None of the above
Make your selection or type a composer package name and version (n): 2
Which config center do you want to use ?
[1] Apollo
[2] Aliyun ACM
[n] None of the above
Make your selection or type a composer package name and version (n): 1
Do you want to use hyperf/constants component ?
[1] yes
[n] None of the above
Make your selection (n): 1
Do you want to use hyperf/async-queue component ? (A simple redis queue component)
[1] yes
[n] None of the above
Make your selection or type a composer package name and version (n): 1
Do you want to use hyperf/amqp component ?
[1] yes
[n] None of the above
Make your selection or type a composer package name and version (n): 1
Do you want to use hyperf/model-cache component ?
[1] yes
[n] None of the above
Make your selection or type a composer package name and version (n): 1
Do you want to use hyperf/elasticsearch component ?
[1] yes
[n] None of the above
Make your selection or type a composer package name and version (n): n
Do you want to use hyperf/tracer component ? (A open tracing protocol component, adapte with Zipkin etc.)
[1] yes
[n] None of the above
Make your selection or type a composer package name and version (n): 1
2闹究、搭建 gateway 服務(wù)消費者
composer create-project hyperf/hyperf-skeleton gateway
Which RPC protocol do you want to use ?
[1] JSON-RPC with Service Governance
[2] JSON-RPC
[3] gRPC
[n] None of the above
Make your selection or type a composer package name and version (n): 2
Which config center do you want to use ?
[1] Apollo
[2] Aliyun ACM
[n] None of the above
Make your selection or type a composer package name and version (n): 1
Do you want to use hyperf/constants component ?
[1] yes
[n] None of the above
Make your selection (n): 1
Do you want to use hyperf/async-queue component ? (A simple redis queue component)
[1] yes
[n] None of the above
Make your selection or type a composer package name and version (n): 1
Do you want to use hyperf/amqp component ?
[1] yes
[n] None of the above
Make your selection or type a composer package name and version (n): 1
Do you want to use hyperf/model-cache component ?
[1] yes
[n] None of the above
Make your selection or type a composer package name and version (n): 1
Do you want to use hyperf/elasticsearch component ?
[1] yes
[n] None of the above
Make your selection or type a composer package name and version (n): n
Do you want to use hyperf/tracer component ? (A open tracing protocol component, adapte with Zipkin etc.)
[1] yes
[n] None of the above
Make your selection or type a composer package name and version (n): 1
二、JSON RPC服務(wù)開發(fā)與配置
1食店、calculate
功能開發(fā)
app
目錄結(jié)構(gòu)
app
Constants
Controller
Exception
JsonRpc
CalculatorService.php
CalculatorServiceInterface.php
Listener
Model
Process
app\JsonRpc\CalculatorService.php
<?php
namespace App\JsonRpc;
use Hyperf\RpcServer\Annotation\RpcService;
/**
* Class CalculatorService
* @RpcService(name="CalculatorService", protocol="jsonrpc", server="jsonrpc")
*/
class CalculatorService implements CalculatorServiceInterface
{
public function add(int $v1, int $v2): int
{
return $v1 + $v2;
}
}
app\JsonRpc\CalculatorServiceInterface.php
<?php
declare(strict_types=1);
namespace App\JsonRpc;
interface CalculatorServiceInterface
{
public function add(int $v1, int $v2): int;
}
calculate 服務(wù)配置
config\autoload\server.php
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://doc.hyperf.io
* @contact group@hyperf.io
* @license https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
*/
use Hyperf\Server\Server;
use Hyperf\Server\SwooleEvent;
return [
'mode' => SWOOLE_PROCESS,
'servers' => [
[
'name' => 'jsonrpc',
'type' => Server::SERVER_BASE,
'host' => '0.0.0.0',
'port' => 9501,
'sock_type' => SWOOLE_SOCK_TCP,
'callbacks' => [
SwooleEvent::ON_RECEIVE => [Hyperf\JsonRpc\TcpServer::class, 'onReceive'],
],
'settings' => [
'open_eof_split' => true,
'package_eof' => "\r\n",
]
],
],
'settings' => [
'enable_coroutine' => true,
'worker_num' => swoole_cpu_num(),
'pid_file' => BASE_PATH . '/runtime/hyperf.pid',
'open_tcp_nodelay' => true,
'max_coroutine' => 100000,
'open_http2_protocol' => true,
'max_request' => 100000,
'socket_buffer_size' => 2 * 1024 * 1024,
],
'callbacks' => [
SwooleEvent::ON_BEFORE_START => [Hyperf\Framework\Bootstrap\ServerStartCallback::class, 'beforeStart'],
SwooleEvent::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'],
SwooleEvent::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'],
],
];
2渣淤、gateway 消費者功能開發(fā)
app 目錄結(jié)構(gòu)
app
Constants
Controller
IndexController.php
Exception
JsonRpc
CalculatorServiceInterface.php
Listener
Model
Process
app\JsonRpc\CalculatorServiceInterface.php
<?php
declare(strict_types=1);
namespace App\JsonRpc;
interface CalculatorServiceInterface
{
public function add(int $v1, int $v2): int;
}
config\routes.php
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://doc.hyperf.io
* @contact group@hyperf.io
* @license https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
*/
use Hyperf\HttpServer\Router\Router;
Router::addRoute(['GET', 'POST', 'HEAD'], '/', 'App\Controller\IndexController@index');
Router::get('/add', 'App\Controller\IndexController@add');
app\Controller\IndexController.php
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://doc.hyperf.io
* @contact group@hyperf.io
* @license https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
*/
namespace App\Controller;
use Hyperf\Utils\Context;
use Hyperf\Utils\Coroutine;
use Hyperf\Utils\Parallel;
use Hyperf\Utils\ApplicationContext;
use App\JsonRpc\CalculatorServiceInterface;
use App\JsonRpc\MathValue;
class IndexController extends AbstractController
{
public function index()
{
$user = $this->request->input('user', 'Hyperf');
$method = $this->request->getMethod();
return [
'method' => $method,
'message' => "Hello {$user}.",
];
}
public function add()
{
$client = ApplicationContext::getContainer()->get(CalculatorServiceInterface::class);
$value = $client->add(10, 20);
return $value;
}
}
gateway 服務(wù)配置
config\autoload\server.php
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://doc.hyperf.io
* @contact group@hyperf.io
* @license https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
*/
use Hyperf\Server\Server;
use Hyperf\Server\SwooleEvent;
return [
'mode' => SWOOLE_PROCESS,
'servers' => [
[
'name' => 'http',
'type' => Server::SERVER_HTTP,
'host' => '0.0.0.0',
'port' => 9500,
'sock_type' => SWOOLE_SOCK_TCP,
'callbacks' => [
SwooleEvent::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'],
],
],
],
'settings' => [
'enable_coroutine' => true,
'worker_num' => swoole_cpu_num(),
'pid_file' => BASE_PATH . '/runtime/hyperf.pid',
'open_tcp_nodelay' => true,
'max_coroutine' => 100000,
'open_http2_protocol' => true,
'max_request' => 100000,
'socket_buffer_size' => 2 * 1024 * 1024,
],
'callbacks' => [
SwooleEvent::ON_BEFORE_START => [Hyperf\Framework\Bootstrap\ServerStartCallback::class, 'beforeStart'],
SwooleEvent::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'],
SwooleEvent::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'],
],
];
config\autoload\services.php
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://doc.hyperf.io
* @contact group@hyperf.io
* @license https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
*/
return [
'consumers' => [
[
// name 需與服務(wù)提供者的 name 屬性相同
'name' => 'CalculatorService',
// 服務(wù)接口名,可選吉嫩,默認值等于 name 配置的值价认,如果 name 直接定義為接口類則可忽略此行配置,如 name 為字符串則需要配置 service 對應(yīng)到接口類
'service' => \App\JsonRpc\CalculatorServiceInterface::class,
// 對應(yīng)容器對象 ID率挣,可選刻伊,默認值等于 service 配置的值,用來定義依賴注入的 key
'id' => \App\JsonRpc\CalculatorServiceInterface::class,
// 服務(wù)提供者的服務(wù)協(xié)議椒功,可選捶箱,默認值為 jsonrpc-http
'protocol' => 'jsonrpc',
// 負載均衡算法,可選动漾,默認值為 random
'load_balancer' => 'random',
// 這個消費者要從哪個服務(wù)中心獲取節(jié)點信息丁屎,如不配置則不會從服務(wù)中心獲取節(jié)點信息
// 'registry' => [
// 'protocol' => 'consul',
// 'address' => 'http://127.0.0.1:8500',
// ],
// 如果沒有指定上面的 registry 配置,即為直接對指定的節(jié)點進行消費旱眯,通過下面的 nodes 參數(shù)來配置服務(wù)提供者的節(jié)點信息
'nodes' => [
['host' => '127.0.0.1', 'port' => 9501],
],
]
],
];
三晨川、服務(wù)啟動與通信演示
1、啟動 calculate
服務(wù)
root@cosyphp-VirtualBox:~# cd /home/wwwroot/calculate/
root@cosyphp-VirtualBox:/home/wwwroot/calculate# php bin/hyperf.php start
2删豺、啟動 gateway 服務(wù)
root@cosyphp-VirtualBox:~# cd /home/wwwroot/gateway/
root@cosyphp-VirtualBox:/home/wwwroot/gateway# php bin/hyperf.php start
3共虑、請求 gateway 服務(wù)
root@cosyphp-VirtualBox:~# curl http://127.0.0.1:9500/add
30
root@cosyphp-VirtualBox:~#
四、各服務(wù)關(guān)系總覽
使用阿里云配置中心的配置呀页。
阿里云配置中心配置文件內(nèi)容對象會直接覆蓋到本機config對象妈拌。以后修改配置信息就不需要重啟服務(wù)了。
安裝依賴
composer require hyperf/config-aliyun-acm
config/autoload 文件夾內(nèi)增加一個 aliyun_acm.php文件內(nèi)容如下:
<?php
return [
// 是否開啟配置中心的接入流程蓬蝶,為 true 時會自動啟動一個 ConfigFetcherProcess 進程用于更新配置
'enable' => true,
// 是否使用獨立進程來拉取config尘分,如果否則將在worker內(nèi)以協(xié)程方式拉取
'use_standalone_process' => true,
// 配置更新間隔(秒)
'interval' => 5,
// 阿里云 ACM 斷點地址猜惋,取決于您的可用區(qū)
'endpoint' => env('ALIYUN_ACM_ENDPOINT', 'acm.aliyun.com'),
// 當前應(yīng)用需要接入的 Namespace
'namespace' => env('ALIYUN_ACM_NAMESPACE', '733e4119-6098-4491-9959a866ceb24'),
// 您的配置對應(yīng)的 Data ID
'data_id' => env('ALIYUN_ACM_DATA_ID', 'hyperf-demo'),
// 您的配置對應(yīng)的 Group
'group' => env('ALIYUN_ACM_GROUP', 'DEFAULT_GROUP'),
// 您的阿里云賬號的 Access Key
'access_key' => env('ALIYUN_ACM_AK', 'LTAI4G8MwXoLGd'),
// 您的阿里云賬號的 Secret Key
'secret_key' => env('ALIYUN_ACM_SK', 'YXLViuYKqM5WoRrCon4U'),
];
或者在根目錄.env 添加:
ALIYUN_ACM_NAMESPACE=733e4119-6098-4491-9950-4b24
ALIYUN_ACM_DATA_ID=hyperf-demo
ALIYUN_ACM_GROUP=DEFAULT_GROUP
ALIYUN_ACM_AK=LTAI4G8MwXosb2S
ALIYUN_ACM_SK=YXLViuYKqM5W
然后