swoft1.x RPC 创建服务端与客户端

RPC的作用就是远程调用,也就是接口。

需要准备的

  • 俩台虚拟机,主要用来测试不同ip的。也不是必须,只是便于理解。
  • 俩台虚拟机都要有一份swoft。

我们先使用swoft里的domo做讲解,然后再自己做一遍。

此时
虚拟机A的IP:192.168.0.135
虚拟机B的IP:192.168.0.134

虚拟机A (客户端)

首先,我们打开这三个文件

图中88行那改成你虚拟机B的ip和端口。

DemoInterface.php:定义接口
DemoService.php:实现定义的接口
这俩个让你打开是让你看的,无需做修改,你只需修改 .env 里的,改好重启服务。
DemoService.php里的类注释有一个@Service(),这个是配置服务端版本号的,@Service()不填默认为0。用法看下面的客户端。

至此,服务端建立。
啥是服务端?
就是提供服务的。调用这个服务的叫做客户端。

虚拟机B(服务端)
虚拟机只需启动就可以了

php bin/swoft rpc:start


浏览器访问(这个页面是一个普通的控制器)
修改客户端 .env HTTP_PORT=8081

http://192.168.0.135:8081/rpc/call

 

 至此,客户端也成功调用到了。
你想知道是不是真的成功了?那很简单,你把服务端的swoft停掉再访问就知道啦。
下面打开的是上面访问的控制器

 

 

@Reference(name=“user”, version=“1.0.1”)
name:服务名称
version:服务版本号

好了,我们来做服务端和客户端吧!

服务端说明
需要定义一个接口,然后实现这个接口。

定义接口

创建swoft/app/Lib/TestInterface.php
 

<?php

namespace App\Lib;

use Swoft\Core\ResultInterface;

interface TestInterface
{
    public function getStr(string $str);

}

实现接口
创建 swoft/app/Services/TestService.php

 

<?php

namespace App\Services;

use App\Lib\TestInterface;
use Swoft\Rpc\Server\Bean\Annotation\Service;

/**
 * @Service()
 */
class TestService implements TestInterface
{
    public function getStr(string $str)
    {
        return ['我是服务端的' . $str];
    }

}

客户端说明
1、从服务端拷贝一份TestInterface.php 到客户端swoft/app/Lib/TestInterface.php,也就是把文件拉进去
2、将三个User的拷贝一份,把User的都改成Test
和服务端不同的是客户端需要有连接池和熔断器。
连接池和熔断器的名称要一样。
连接池由两部分组成,“连接池”和“连接池配置”。

 

TestBreaker.php改@Breaker(“user”)为@Breaker(“test”),改类名
TestServicePool.php改@Pool(name=“user”)为@Pool(name=“test”),改类名
TestPoolConfig.php 改类名

3、创建测试控制器 swoft/app/Controllers/TestController.php
 

<?php

namespace App\Controllers;

use Swoft\Http\Message\Server\Request;
use Swoft\Http\Server\Bean\Annotation\Controller;
use Swoft\Http\Server\Bean\Annotation\RequestMapping;
use Swoft\Http\Server\Bean\Annotation\RequestMethod;
use Swoft\Rpc\Client\Bean\Annotation\Reference;
use App\Lib\TestInterface;
/**
 * Class TestController
 * @Controller("/test")
 */
class TestController
{
    /**
     * @Reference(name="test")
     *
     * @var TestInterface
     */
    private $testService;

    /**
     * @RequestMapping(route="test")
     */
    public function test()
    {
        $result  = $this->testService->getStr('-这儿是客户端');
        return [
            'result'  => $result,
        ];
    }

}

服务端启动

php bin/swoft rpc:start

 

客户端启动
修改客户端 .env HTTP_PORT=8081

php bin/swoft start

访问

192.168.0.135:8081/test/test

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章