docker環(huán)境前面有寫忆植,這里就不重復(fù)了
首先拉取搭建 hyperf 服務(wù)端
創(chuàng)建項(xiàng)目
composer create-project hyperf/hyperf-skeleton server-provider
創(chuàng)建的時候選擇rpc
服務(wù)
也可以在項(xiàng)目創(chuàng)建完成的時候 composer 去拉取
composer require hyperf/json-rpc
composer require hyperf/rpc-server
安裝注冊中心 Nacos 適配器
composer require hyperf/service-governance-nacos
發(fā)布組件config/autoload/services.php
php bin/hyperf.php vendor:publish hyperf/service-governance-nacos
配置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' => [],
'providers' => [],
'drivers' => [
'consul' => [
'uri' => 'http://172.17.0.8:8500',
'token' => '',
'check' => [
'deregister_critical_service_after' => '90m',
'interval' => '1s',
],
],
'nacos' => [
// docker 容器內(nèi)地址 docker insepct 容器名 or 容器id 查看
'host' => '172.17.0.4',
// nacos默認(rèn)端口
'port' => 8848,
// nacos賬號
'username' => 'nacos',
// nacos密碼
'password' => 'nacos',
'guzzle' => [
'config' => null,
],
// 命名空間,public為默認(rèn)系統(tǒng)空間严里,登錄nacos 配置列表-配置管理可見
'group_name' => 'public',
'heartbeat' => 5,
'ephemeral' => false // 是否注冊臨時實(shí)例
],
],
];
安裝配置中心 nacos 配置器
composer require hyperf/config-center
composer require hyperf/config-nacos
composer require hyperf/config-apollo
發(fā)布nacos配置器組件config/autoload/config_center.php
php hyperf.php vendor:publish hyperf/config-center
<?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\ConfigApollo\PullMode; 這個類暫時用不上吨岭,可以注釋
use Hyperf\ConfigCenter\Mode;
return [
'enable' => (bool) env('CONFIG_CENTER_ENABLE', true),
// 注意這里服務(wù)我們是用的nacos服務(wù)虑粥,所以默認(rèn)寫成nacos恭金,也可以在.nev文件下去配置
'driver' => env('CONFIG_CENTER_DRIVER', 'nacos'),
'mode' => env('CONFIG_CENTER_MODE', Mode::PROCESS),
'drivers' => [
'nacos' => [
'driver' => Hyperf\ConfigNacos\NacosDriver::class,
// 配置合并方式项贺, 支持覆蓋和合并
'merge_mode' => Hyperf\ConfigNacos\Constants::CONFIG_MERGE_OVERWRITE,
'interval' => 3,
// 如果對應(yīng)的映射key沒有設(shè)置鳞仙,則使用默認(rèn)的key
'default_key' => 'nacos_config',
'listener_config' => [
// dataId, group, tenant, type, content
'nacos_config' => [
// corresponding with service.namespaceId
// 命名空間
'tenant' => 'public',
// DATA-ID
'data_id' => 'hyperf-service-config',
'group' => 'DEFAULT_GROUP',
'type' => 'json'
],
'nacos_config.data' => [
'data_id' => 'hyperf-service-config-yml',
'group' => 'DEFAULT_GROUP',
'type' => 'json'
]
],
'client' => [
// nacos server url like https://nacos.hyperf.io, Priority is higher than host:port
// 'uri' => '',
'host' => '172.17.0.4',
'port' => 8848,
// nacos賬號
'username' => 'nacos',
// nacos密碼
'password' => 'nacos',
'guzzle' => [
'config' => null,
],
],
],
// 以前注冊中心用不上寇蚊,可以注釋,不然又要去拉很多包
/*
'apollo' => [
'driver' => Hyperf\ConfigApollo\ApolloDriver::class,
'pull_mode' => PullMode::INTERVAL,
'server' => 'http://127.0.0.1:9080',
'appid' => 'test',
'cluster' => 'default',
'namespaces' => [
'application',
],
'interval' => 5,
'strict_mode' => false,
'client_ip' => \Hyperf\Utils\Network::ip(),
'pullTimeout' => 10,
'interval_timeout' => 1,
],
'aliyun_acm' => [
'driver' => Hyperf\ConfigAliyunAcm\AliyunAcmDriver::class,
'interval' => 5,
'endpoint' => env('ALIYUN_ACM_ENDPOINT', 'acm.aliyun.com'),
'namespace' => env('ALIYUN_ACM_NAMESPACE', ''),
'data_id' => env('ALIYUN_ACM_DATA_ID', ''),
'group' => env('ALIYUN_ACM_GROUP', 'DEFAULT_GROUP'),
'access_key' => env('ALIYUN_ACM_AK', ''),
'secret_key' => env('ALIYUN_ACM_SK', ''),
'ecs_ram_role' => env('ALIYUN_ACM_RAM_ROLE', ''),
],
'etcd' => [
'driver' => Hyperf\ConfigEtcd\EtcdDriver::class,
'packer' => Hyperf\Utils\Packer\JsonPacker::class,
'namespaces' => [
'/application',
],
'mapping' => [
// etcd key => config key
'/application/test' => 'test',
],
'interval' => 5,
'client' => [
# Etcd Client
'uri' => 'http://127.0.0.1:2379',
'version' => 'v3beta',
'options' => [
'timeout' => 10,
],
],
],
'zookeeper' => [
'driver' => Hyperf\ConfigZookeeper\ZookeeperDriver::class,
'server' => env('ZOOKEEPER_SERVER', '127.0.0.1:2181'),
'path' => env('ZOOKEEPER_CONFIG_PATH', '/conf'),
'interval' => 5,
],
*/
],
];
nacos 客戶端去配置
根據(jù)自己需要編寫配置
服務(wù)配置完成后棍好,編寫測試代碼
在項(xiàng)目根目錄下新建app/JsonRpc
目錄(根據(jù)自己需求)
再新建app/JsonRpc/InterfaceImp
編寫代碼
app/JsonRpc/OrderServiceInterface.php
<?php
declare(strict_types=1);
namespace App\JsonRpc;
interface OrderServiceInterface {
public function userInfo();
}
編寫代碼
app/JsonRpc/InterfaceImp/OrderService
<?php
declare(strict_types=1);
namespace App\JsonRpc\InterfaceImp;
use App\JsonRpc\OrderServiceInterface;
use Hyperf\RpcServer\Annotation\RpcService;
/**
* 服務(wù)提供者 publicTo 為nacos
* 注意仗岸,如希望通過服務(wù)中心來管理服務(wù),需在注解內(nèi)增加 publishTo 屬性
* @RpcService(name="OrderService", protocol="jsonrpc", server="jsonrpc",publishTo="nacos")
*/
class OrderService implements OrderServiceInterface
{
protected $list = [
['id'=>1, 'name'=>'Mr.Li', 'age' => 20],
['id'=>2, 'name'=>'Mr.Zhang', 'age' => 30]
];
public function userInfo()
{
return $this->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需要和接口實(shí)現(xiàn)類的server對應(yīng)
'name' => 'jsonrpc',
'type' => Server::SERVER_BASE,
'host' => '0.0.0.0',
'port' => 9512,
'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'],
],
];
獲取hyperf配置中心配置
// Config 組件提供了三種方式獲取配置借笙,通過 Hyperf\Config\Config 對象獲取扒怖、通過 @Value 注解獲取和通過 config(string $key, $default) 函數(shù)獲取。
// 配置好配置中心后Hypef 自動映射到config里面,直接獲取就可以
//eg:: nacos_config 為如上配置的配置名稱
config('nacos_config.data_id')
偽代碼
public function getConfig(): array
{
$data = config('nacos_config.data_id');
return ['msg' => 'success', 'data' => $data];
}
獲取配置
啟動服務(wù)端
php bin/hyperf.php start
查看 nacos 客戶端是否有我們注冊的服務(wù)
可以看到我們OrderService
服務(wù)已經(jīng)注冊上了
有個問題沒有解決业稼,nacos的ephemeral
配置不管寫成 true or false
都是注冊的臨時實(shí)例
拉取 hyperf 客戶端
composer create-project hyperf/hyperf-skeleton server-consumer
可以創(chuàng)建的時候選取
創(chuàng)建完項(xiàng)目拉取
composer require hyperf/json-rpc
composer require hyperf/rpc-client
composer require hyperf/service-governance-nacos
發(fā)布組件
配置services.php
<?php
declare(strict_types=1);
return [
'enable' => [
'discovery' => true,
'register' => true,
],
'consumers' => [
[
// 服務(wù)名稱盗痒,需要對應(yīng)上服務(wù)端的名稱
'name' => 'OrderService',
'service' => \App\JsonRpc\OrderServiceInterface::class,
'id' => \App\JsonRpc\OrderServiceInterface::class,
'protocol' => 'jsonrpc',
'registry' => [
// 使用 nacos
'protocol' => 'nacos',
'address' => 'http://172.17.0.4:8848',
]
],
],
'providers' => [],
'drivers' => [
'consul' => [
'uri' => 'http://172.17.0.8:8500',
'token' => '',
'check' => [
'deregister_critical_service_after' => '90m',
'interval' => '1s',
],
],
'nacos' => [
'host' => '172.17.0.4',
'port' => 8848,
// nacos賬號
'username' => 'nacos',
// nacos密碼
'password' => 'nacos',
'guzzle' => [
'config' => null
],
'group_name' => 'public',
'heartbeat' => 5
]
]
];
編寫客戶端代碼
app\JsonRpc\OrderServiceInterface.php
<?php
declare(strict_types=1);
namespace App\JsonRpc;
interface OrderServiceInterface {
public function userInfo();
}
編寫測試代碼 在控制器中
App\Controller
<?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\OrderServiceInterface;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Utils\ApplicationContext;
/**
* @AutoController()
*/
class IndexController extends AbstractController
{
public function rpc(): array
{
$client = ApplicationContext::getContainer()->get(OrderServiceInterface::class);
$res = $client->userInfo();
return ['res' => $res, 'time' => date('Y-m-d H:i:s',time())];
}
}
啟動客戶端
php bin/hyperf.php start
訪問接口
http://127.0.0.1:9513/index/rpc
輸出,測試成功!
測試代碼已經(jīng)上傳至碼云低散,倉庫地址:
https://gitee.com/Michart/rpc-nacos