IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> PHP知识库 -> hyperf 实现简单的jsonrpc和grpc -> 正文阅读

[PHP知识库]hyperf 实现简单的jsonrpc和grpc

hypefr简单介绍
在这里插入图片描述
这里使用docker安装一下hyperf
因为需要容器间通信 用docker创建自己的网络 这里我使用172.172.0.0/24创建hyperf网络
到时候创建hyperfy容器的时候 使用
在这里插入图片描述
这个范围内的网络

docker run --name hyperfServer\
-v /home/wwwroot/default/hyperf1:/data/project \
-p 9505:9505 -itd \
--privileged -u root \
--entrypoint /bin/sh \
--network hyperf --ip 172.172.0.2 \
hyperf/hyperf:7.4-alpine-v3.11-swoole
docker run --name hyperfClient \
-v /home/wwwroot/default/hyperf2:/data/project \
-p 9506:9506 -itd \
--privileged -u root \
--entrypoint /bin/sh \
--network hyperf --ip 172.172.0.3 \
hyperf/hyperf:7.4-alpine-v3.11-swoole

在这里插入图片描述
为什么要创建2个呢
服务有两种角色,一种是 服务提供者(ServiceProvider),即为其它服务提供服务的服务,另一种是 服务消费者(ServiceConsumer),即依赖其它服务的服务,一个服务既可能是 服务提供者(ServiceProvider),同时又是 服务消费者(ServiceConsumer)。而两者直接可以通过 服务契约 来定义和约束接口的调用,在 Hyperf 里,可直接理解为就是一个 接口类(Interface),通常来说这个接口类会同时出现在提供者和消费者下。
这里把hyperfClient容器当做服务消费者 hyperfServer容器当做服务提供者
先进入到hyperfClient容器 安装hyperf
composer create-project hyperf/hyperf-skeleton hyperfClient 在这里插入图片描述
其他组件看需要安装
先使用jsonRpc
hyperfServer容器同理
composer create-project hyperf/hyperf-skeleton hyperfServer

启动一下hyperfClient 容器内启动和宿主机启动都可以 在启动hyperf之前因为hyperfClient 端口是9506
需要修改一下 hyperfClient /config/server.php下的监听端口为9506 默认是9501 在执行
php bin/hyperf.php start
访问一下 ip加端口
在这里插入图片描述
HyperfClient 启动成功
由于 Hyperf 是持久化的 CLI 框架,当您修改完您的代码后,通过 CTRL + C 终止当前启动的进程实例,并重新执行 php bin/hyperf.php start 启动命令即可。为了方便后面的修改代码不用每次都重启安装一下hyperf的Watcher热更新组件

JSON RPC 服务
JSON RPC 是一种基于 JSON 格式的轻量级的 RPC 协议标准,易于使用和阅读。在 Hyperf 里由 hyperf/json-rpc 组件来实现,可自定义基于 HTTP 协议来传输,或直接基于 TCP 协议来传输。

hyperfServer修改监听端口9505开始编写服务提供代码

1.1定义服务提供方式端口
app/config/server.php 使用jsonRpc方式
composer require hyperf/rpc-server

return [
    'mode' => SWOOLE_PROCESS,
    'servers' => [
        [
            'name' => 'jsonrpc-http',
            'type' => Server::SERVER_HTTP,
            'host' => '0.0.0.0',
            'port' => 9505,
            'sock_type' => SWOOLE_SOCK_TCP,
            'callbacks' => [
                Event::ON_REQUEST => [\Hyperf\JsonRpc\HttpServer::class, 'onRequest'],
            ],
        ],
    ],

1.2 定义服务接口
app/jsonRpc/CalculatorServiceInterface

<?php

namespace App\JsonRpc;

interface CalculatorServiceInterface
{
    public function add(int $a, int $b): int;

    public function reduce(int $a, int $b): int;
}

1.3 实现接口定义服务类
app/jsonRpc/CalculatorService 先不用服务治理中心

<?php

namespace App\JsonRpc;

use Hyperf\RpcServer\Annotation\RpcService;

/**
 * 注意,如希望通过服务中心来管理服务,需在注解内增加 publishTo 属性
 * @RpcService(name="CalculatorService", protocol="jsonrpc-http", server="jsonrpc-http")
 */
class CalculatorService implements CalculatorServiceInterface
{
    // 实现一个加法方法,这里简单的认为参数都是 int 类型
    public function add(int $a, int $b): int
    {
        // 这里是服务方法的具体实现
        return $a + $b;
    }

    public function reduce(int $a, int $b): int
    {
        // TODO: Implement reduce() method.
        return $a - $b;
    }
}

在这里插入图片描述

hyperfClient修改监听端口9505开始编写服务提供代码 composer require hyperf/rpc-client
2.1定义服务消费者
config/autoload/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 [
    'consumers' => [
        [
            // The service name, this name should as same as with the name of service provider.
            'name' => 'CalculatorService',
            'protocol' => 'jsonrpc-http',
            // 负载均衡算法,可选,默认值为 random
            'load_balancer' => 'random',
            // If `registry` is missing, then you should provide the nodes configs.
            'nodes' => [
                // Provide the host and port of the service provider.
                 ['host' => '10.225.137.105', 'port' => 9505]
            ],
        ],
    ],
];

nodes配置指定服务提供者的ip和端口

2.2定义接口类 和服务提供者一样
2.3实现服务消费者类

<?php

namespace App\JsonRpc;

use Hyperf\RpcClient\AbstractServiceClient;

class CalculatorServiceConsumer extends AbstractServiceClient implements CalculatorServiceInterface
{
    /**
     * 定义对应服务提供者的服务名称
     * @var string
     */
    protected $serviceName = 'CalculatorService';

    /**
     * 定义对应服务提供者的服务协议
     * @var string
     */
    protected $protocol = 'jsonrpc-http';

    /**
     * 两数相加
     * @param int $a
     * @param int $b
     * @return int  $a + $b
     */
    public function add(int $a, int $b): int
    {
        return $this->__request(__FUNCTION__, compact('a', 'b'));
    }

    /**
     * 两数相减
     * @param int $a
     * @param int $b
     * @return int $a - $b
     */
    public function reduce(int $a, int $b): int
    {
        return $this->__request(__FUNCTION__, compact('a', 'b'));
    }
}

在这里插入图片描述
2.4编写控制器
app/Controller/TestJsonRpcController

<?php

namespace App\Controller;

use App\JsonRpc\CalculatorServiceInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;

/**
 * @AutoController()
 * Class TestJsonRpcController
 * @package App\Controller
 */
class TestJsonRpcController extends AbstractController
{
    /**
     * @Inject()
     * @var CalculatorServiceInterface
     */
    private $calculatorService;

    /**
     * 两树相加
     * @return int
     */
    public function add()
    {
        $data= $this->calculatorService->add($this->request->query('a', 1), $this->request->query('b', 2));
        return [
            'result' => $data,
        ];
    }

    /**
     * 两树相减
     * @return int
     */
    public function reduce()
    {
        return $this->calculatorService->reduce($this->request->query('a', 1), $this->request->query('b', 2));
    }
}

使用hyperf的注解路由和inject注解注入

2.5测试一下 jsonRpc
在这里插入图片描述
在这里插入图片描述
简单的实现了jsonrpc

GRPC
gRPC是一个高性能、开源、通用的RPC框架。基于HTTP/2协议标准设计开发,默认采用Protocol Buffers数据序列化协议Protocol Buffers基本语法,支持多种开发语言。gRPC提供了一种简单的方法来精确的定义服务,并且为客户端和服务端自动生成可靠的功能库

grpc 四种服务类型:
1、简单方式:这就是一般的 rpc 调用,一个请求对象对应一个返回对象

2、服务端流式(Sever-side streaming )

3、客户端流式(Client-side streaming RPC)

4、双向流式(Bidirectional streaming RPC)

下面将实现grpc简单调用

1.1在hyperfServer和hyperClient 定义好 proto 文件 grpc.proto
使用 protoc 生成示例代码
在这里插入图片描述
protoc --php_out=grpc ./grpc.proto 定义在grpc目录

服务提供者
1.2
hyperfServer容器 composer require hyperf/grpc-server 安装grpc组件
定义config/server.php 文件
在这里插入图片描述
在这里插入图片描述
1.3编写服务方法 app/Controller/HiController

<?php
/*
 * @Author: yueGod
 * @Date: xxx
 * @LastEditors: yueGod
 * @LastEditTime:xxx
 * @Description: 
 */


namespace App\Controller;
use Grpc\HiReply;
use Grpc\HiUser;

class HiController
{
    public function sayHello(HiUser $user)
    {
        $message = new HiReply();
        $message->setMessage("Hello".$user->getName());
        $message->setUser($user);
        return $message;
    }

}

2.1服务消费者
composer require hyperf/grpc-client

<?php
namespace App\GrpcClient;
use Grpc\HiUser;
use App\GrpcClient\HiClient;

class GrpcController
{
    public function hello()
    {
        // 这个client是协程安全的,可以复用
        $client = new  \App\GrpcClient\HiClient('10.225.137.105:9505', [
            'credentials' => null,
        ]);

        $request = new \Grpc\HiUser();
        $request->setName('hyperf');
        $request->setSex(1);

        /**
         * @var \Grpc\HiReply $reply
         */
        list($reply, $status) = $client->sayHello($request);

        $message = $reply->getMessage();
        $user = $reply->getUser();

        return [
            'message'=>$message,
            'user'=>$user
        ];
    }
}
<?php
namespace App\GrpcClient;

use Hyperf\GrpcClient\BaseClient;
use Grpc\HiUser;
use Grpc\HiReply;


class HiClient extends BaseClient
{
    public function sayHello(HiUser $argument)
    {
        return $this->_simpleRequest(
            '/grpc.hi/sayHello',
            $argument,
            [HiReply::class, 'decode']
        );
    }
}

2.2 定义路由
Router::get(’/hello-grpc’, ‘App\GrpcClient\GrpcController@hello’);

3.1测试一下

在这里插入图片描述

  PHP知识库 最新文章
Laravel 下实现 Google 2fa 验证
UUCTF WP
DASCTF10月 web
XAMPP任意命令执行提升权限漏洞(CVE-2020-
[GYCTF2020]Easyphp
iwebsec靶场 代码执行关卡通关笔记
多个线程同步执行,多个线程依次执行,多个
php 没事记录下常用方法 (TP5.1)
php之jwt
2021-09-18
上一篇文章           查看所有文章
加:2021-07-16 10:58:33  更:2021-07-16 11:05:03 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年4日历 -2024/4/27 14:01:15-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码