think-swoole扩展实现在传统php-fpm环境调用rpc服务
码农天地 -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
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。
php介绍
PHP即“超文本预处理器”,是一种通用开源脚本语言。PHP是在服务器端执行的脚本语言,与C语言类似,是常用的网站编程语言。PHP独特的语法混合了C、Java、Perl以及 PHP 自创的语法。利于学习,使用广泛,主要适用于Web开发领域。
上一篇: 小程序-实现折叠面板-手风琴效果