会点 Vue.js ThinkPHP Workerman Swoole 的搬运工

0%

ThinkPHP 6 RPC 例子教程

RPC 依赖Swoole环境

安装

1
composer require topthink/think-swoole

创建接口

1
2
3
4
5
6
7
8
9
10
11
12
13
namespace app\service;

interface OperationInterface
{
/**
* 加法运算
*
* @param [type] $a
* @param [type] $b
* @return void
*/
public function add($a, $b);
}

创建服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace app\service;

/**
* 这是个运算服务
*
*/
class OperationService implements OperationInterface
{
/**
* 执行加法运算
*
* @param [type] $a
* @param [type] $b
* @return void
*/
public function add($a, $b)
{
return $a + $b;
}
}

配置

swoole.php

1
2
3
4
5
6
7
8
9
'rpc'        => [
'server' => [
'enable' => true,
'port' => 9000,
'services' => [
'OperationService' => \app\service\OperationService::class
],
]
],

调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

namespace app\controller;

use app\BaseController;
use think\swoole\rpc\client\Client;

/**
* @package app\controllers
*
*/
class Index extends BaseController
{

public function index(OperationService $service)
{
$service = $service->add([1, 2]);
var_dump($service);
}
}

启动

1
php think swoole

访问 http://localhost:9000