官方項目地址https://github.com/top-think/think-swoolephp
tp官方的think-swoole擴展提供了一個rpc服務和客戶端,可是他的rpc客戶端只能在swoole的環境下運行git
可是swoole官方是提供了同步客戶端/swoole/client的,若是把框架的client更換成官方的同步client,應該就能實如今傳統的fpm環境中調用swoole環境下的rpc。github
<?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。
原理就是檢測當前是否在fpm環境,是的話手動註冊rpc服務,官方的擴展是要使用php think swoole start命令啓動時,才能在代碼中訪問rpc接口的,註冊了這個服務之後,就能夠在fpm環境下使用了,而且不影響其餘功能。thinkphp
區別:
1官方擴展使用的是鏈接池,這裏去掉了。
2官方擴展使用的是協程客戶端,這裏使用的是同步客戶端api
用法:
跟官方一致php框架