Hyperf jsonrpc 服务的搭建
2021-02-07 06:15
标签:name nts odi 执行 配置 soc ann server back 如果需要使用 consul来管理服务,则需要做如下操作 执行完毕后会形成一个配置文件 consul.php 3).Conusmer修改配置 Hyperf jsonrpc 服务的搭建 标签:name nts odi 执行 配置 soc ann server back 原文地址:https://www.cnblogs.com/bobobobobo/p/13093794.html准备工作
1、所需类库
2、工具
3、Provider的配置
1、服务提供类
php
namespace App\Rpc;
use Hyperf\RpcServer\Annotation\RpcService;
/**
* @RpcService(name="CalculatorService",protocol="jsonrpc-http",server="jsonrpc-http")
*/
class CalculatorService implements CalculatorServiceInterface
{
public function add(int $a, int $b): int
{
return $a + $b;
}
public function minus(int $a, int $b): int
{
return $a - $b;
}
} 2、接口类
php
namespace App\Rpc;
interface CalculatorServiceInterface
{
public function add(int $a, int $b): int;
public function minus(int $a, int $b): int;
}
‘servers‘ => [
...
[
‘name‘ => ‘jsonrpc-http‘,
‘type‘ => Server::SERVER_HTTP,
‘host‘ => ‘0.0.0.0‘,
‘port‘ => 9802,
‘sock_type‘ => SWOOLE_SOCK_TCP,
‘callbacks‘ => [
SwooleEvent::ON_REQUEST => [Hyperf\JsonRpc\HttpServer::class, ‘onRequest‘],
],
],
],
3、Consumer 的配置
1、接口类
php
namespace App\Rpc;
interface CalculatorServiceInterface
{
public function add(int $a, int $b): int;
public function minus(int $a, int $b): int;
}
2、配置文件 services.php
3、调用
php
namespace App\Controller;
use App\Rpc\CalculatorServiceInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
/**
* @AutoController()
*/
class IndexController extends AbstractController
{
/**
* @Inject()
* @var CalculatorServiceInterface
*/
private $calculatorService;
public function rpc()
{
return $this->calculatorService->minus(10,2);
}
}
4、使用consul
1).修改Provider具体的服务类,注解添加属性 publishTo
/**
* @RpcService(name="CalculatorService",protocol="jsonrpc-http",server="jsonrpc-http",publishTo="consul")
*/ 2).Provider服务发布
php bin/hyperf.php vendor:publish hyperf/consul
return [
‘consumers‘ => [
[
‘name‘ => ‘CalculatorService‘,
‘service‘ => \App\Rpc\CalculatorServiceInterface::class,
registry‘ => [
‘protocol‘ => ‘consul‘, ‘address‘ => ‘http://127.0.0.1:8500‘,//对应Provider 中 consul.php配置项
]
],
],
]; 4)重新启动Provider和Consumer
下一篇:纯HTML/CSS 实现时钟效果
文章标题:Hyperf jsonrpc 服务的搭建
文章链接:http://soscw.com/index.php/essay/52054.html