关于swoole:thinkswoole扩展实现在传统phpfpm环境调用rpc服务

36次阅读

共计 2333 个字符,预计需要花费 6 分钟才能阅读完成。

https://github.com/top-think/think-swoole

tp 官网的 think-swoole 提供了一个 rpc 服务和客户端,然而他的 rpc 客户端只能在 swoole 的环境下运行

然而 swoole 官网是提供了同步客户端 /swoole/client 的,如果把框架的 client 更换成官网的同步 client,应该就能实现在传统的 fpm 环境中调用 swoole 环境下的 rp~~~~c。

<?php
namespace appservice;
use Exception;
use Generator;
use SwooleClient;
use SwooleCoroutine;
use thinkhelperArr;
use thinkService;
use thinkswooleexceptionRpcClientException;
use thinkswoolePool;
use thinkswoolerpcclientConnector;
use thinkswoolerpcclientGateway;
use thinkswoolerpcclientProxy;
use thinkswoolerpcJsonParser;
use thinkswoolerpcPacker;
use Throwable;
class SwooleRpcServiceLoad extends Service
{public $rpcServices = [];
 /**
 * 注册服务 * * @return mixed
 */ public function register()
 {if (php_sapi_name() == 'fpm-fcgi') {if (file_exists($rpc = $this->app->getBasePath() . 'rpc.php')) {$this->rpcServices = (array)include $rpc;
 }
 } } /**
 * 执行服务 * * @return mixed
 */ public function boot()
 {if (!empty($clients = config('swoole.rpc.client')) && $this->rpcServices) {
 try {foreach ($this->rpcServices as $name => $abstracts) {$parserClass = config("swoole.rpc.client.{$name}.parser", JsonParser::class);
 $parser = $this->app->make($parserClass);
 $gateway = new Gateway($this->createRpcConnector($name), $parser);
 foreach ($abstracts as $abstract) {$this->app->bind($abstract, function () use ($gateway, $name, $abstract) {return $this->app->invokeClass(Proxy::getClassName($name, $abstract), [$gateway]);
 });
 }
 } } catch (Exception | Throwable $e) {}} } protected function createRpcConnector($name)
 {return new class($name) implements Connector {
 public $name;
 public function __construct($name)
 {$this->name = $name;}
 public function sendAndRecv($data)
 {if (!$data instanceof Generator) {$data = [$data];
 }
 $config = config('swoole.rpc.client.' . $this->name);
 $client = new Client(SWOOLE_SOCK_TCP);
 $host = Arr::pull($config, 'host');
 $port = Arr::pull($config, 'port');
 $timeout = Arr::pull($config, 'timeout', 5);
 $client->set([
 'open_length_check' => true,
 'package_length_type' => Packer::HEADER_PACK,
 'package_length_offset' => 0,
 'package_body_offset' => 8,
 ]);
 $client->connect($host, $port, $timeout);
 try {foreach ($data as $string) {if (!$client->send($string)) {$this->onError($client);
 }
 } $response = $client->recv();
 if ($response === false || empty($response)) {$this->onError($client);
 }
 return $response;
 } finally {$client->close();
 }
 } protected function onError(Client $client)
 {$client->close();
 throw new RpcClientException(swoole_strerror($client->errCode), $client->errCode);
 }
 };
 }
}

把下面这个服务在 thinkphp 框架中注册,就能够实现在 fpm 环境下调用 think-swoole 的 rpc

正文完
 0