# 5.7 RPC

RPC（Remote Procedure Call）即远程过程调用,是指网络计算机之间相互调用过程函数,而不需要关心底层的网络通信。MSF的RPC 目前是基于Http协议,当然使用者不需要关心,因为后续有可能会有调整。

MSF实现的RPC具体的基本原则是:

1. 任何类可导出并提供服务
2. RPC Client与RPC Server的类名与方法名一致
3. 任何服务可以很方便的导出自己的类与类方法

## 服务配置

```php
<?php
/**
 * RPC服务配置
 *
 * @author camera360_server@camera360.com
 * @copyright Chengdu pinguo Technology Co.,Ltd.
 */
$config['service']['demo']['host']    = 'http://127.0.0.1:8000';
$config['service']['demo']['timeout'] = 2000;

return $config;
```

示例配置代码：

[https://github.com/pinguo/php-msf-demo/config/docker/rpc.php](https://github.com/pinguo/php-msf-demo/blob/master/config/docker/rpc.php)

## 导出服务

```php
<?php
/**
 * RPC示例Handler
 */
namespace App\Models\Handlers;

use PG\MSF\Models\Model;

class Sum extends Model
{
    public $a;

    public function __construct($a = 0)
    {
        $this->a = $a;
    }

    /**
     * 求和
     *
     * @param array ...$args
     * @return float|int
     */
    public function multi(...$args)
    {
        return array_sum($args);
    }
}
```

示例配置代码：

[https://github.com/pinguo/php-msf-demo/app/Models/Handlers/Sum.php](https://github.com/pinguo/php-msf-demo/blob/master/app/Models/Handlers/Sum.php)

## 调用服务

```php
<?php
/**
 * RPC示例控制器
 *
 * @author camera360_server@camera360.com
 * @copyright Chengdu pinguo Technology Co.,Ltd.
 */

namespace App\Controllers;

use PG\MSF\Controllers\Controller;
use PG\MSF\Client\RpcClient;

class RpcTest extends Controller
{
    public function actionGetSum()
    {
        /**
         * @var RpcClient $client
         */
        $client = $this->getObject(RpcClient::class, ['demo']);
        $sum    = yield $client->handler('sum')->multi(1, 2, 3, 4, 5);
        $this->outputJson($sum);
    }
}
```

`$this->getObject(RpcClient::class, ['demo']);`注意第二个参数表示调用哪一个服务，和配置相对应。

## 并行调用服务

```php
<?php
/**
 * RPC示例控制器
 *
 * @author camera360_server@camera360.com
 * @copyright Chengdu pinguo Technology Co.,Ltd.
 */

namespace App\Controllers;

use PG\MSF\Controllers\Controller;
use PG\MSF\Client\RpcClient;

class RpcTest extends Controller
{
    public function actionConcurrentSum()
    {
        $rpc[] = $this->getObject(RpcClient::class, ['demo'])->handler('sum')->func('multi', 1, 2, 3, 4, 5);
        $rpc[] = $this->getObject(RpcClient::class, ['demo'])->handler('sum')->func('multi', 1, 2, 3, 4);
        $rpc[] = $this->getObject(RpcClient::class, ['demo'])->handler('sum')->func('multi', 1, 2, 3);
        $rpc[] = $this->getObject(RpcClient::class, ['demo'])->handler('sum')->func('multi', 1, 2);

        $sum = yield RpcClient::goConcurrent($rpc);
        $this->outputJson($sum);
    }
}
```

`RpcClient::goConcurrent($rpc);`可以并行发送RPC请求，然后依次获取结果。


# links
  * [目录](../README.md)
  * 上一节: [对象池](5.6-对象池.md)
  * 下一节: [公共库](5.8-公共库.md)