swoft服务端和客户端的创建

#swoft:RPC服务
https://doc.swoft.org/master/zh-CN/rpc-server/index.html

1、第一步:创建接口
https://doc.swoft.org/master/zh-CN/rpc-server/interface.html

app/Lib/目录中创建一个ProductInterface.php,代码如下:

<?php
namespace App\Lib;

use Swoft\Core\ResultInterface;

/**
 * @method ResultInterface deferGetStockQty(int $product_id)
 */
interface ProductInterface
{
    /**
     * 获取商品库存数量
     * @param int $product_id
     * @return mixed
     */
    public function getStockQty(int $product_id);
}

这样就定义了一个Product接口,定义了一个获取商品库存的方法。

2、第二步:实现上面的接口

app/Services/目录中创建ProductService.php,代码如下:

<?php

namespace App\Services;


use App\Lib\ProductInterface;
use Swoft\Core\ResultInterface;
use Swoft\Rpc\Server\Bean\Annotation\Service;

/**
 * @method ResultInterface deferGetStockQty(int $product_id)
 * @Service(version="1.0")
 */
class ProductService implements ProductInterface
{

    /**
     * 获取商品库存数量
     * @param int $product_id
     * @return mixed
     */
    public function getStockQty(int $product_id)
    {
        return 100;
    }
}

这样RPC服务端就完事儿了
#RPC 客户端

1、连接池
https://doc.swoft.org/master/zh-CN/rpc-client/pool.html

app/Pool/目录下,,Swoft框架默认写好了一个叫user的连接池。
之所以叫user是对应config/properties/service.php文件:

<?php

return [
    'user' => [
        'name'        => 'redis',
        'uri'         => [
            '127.0.0.88:8099', #远程PRC服务端地址
        ],
        'minActive'   => 8,
        'maxActive'   => 8,
        'maxWait'     => 8,
        'maxWaitTime' => 3,
        'maxIdleTime' => 60,
        'timeout'     => 8,
        'useProvider' => false,
        'balancer' => 'random',
        'provider' => 'consul',
    ]
];

2、熔断器
https://doc.swoft.org/master/zh-CN/rpc-client/breaker.html

一个服务的熔断器名称要和连接池一致
app/Breaker/目录下,Swoft框架默认写好了一个UserBreaker.php

3、使用
https://doc.swoft.org/master/zh-CN/rpc-client/example.html

官方也给我们提供了示例RpcController.php

    /**
     * @Reference("user")
     *
     * @var DemoInterface
     */
    private $demoService;

注意点:
1、类中属性需要用到我们之前定义的接口(在服务端定义的),所以我们可以直接拷贝过来(不需要拷贝实现)。app/Lib/ProductInterface.php
2、@Reference注解

改动一下示例代码:

    /**
     * @Reference("user")
     *
     * @var ProductInterface
     */
    private $productService;

在控制器方法里:

   /**
     * @RequestMapping(route="test", method=RequestMethod::GET)
     */
    public function test()
    {
    	// 获取product_id为99的商品的库存
        $qty = $this->productService->getStockQty(99);
        return $qty;
    }

这样我们在Swoft客户端访问test方法,就会调用远程服务端的接口。

猜你喜欢

转载自blog.csdn.net/github_26672553/article/details/82784834