要求:

不适用nginx+fastcgi情况下,分布式系统之间如果通讯,如果不阻塞,能并发处理请求

环境:

luman/laravel:5.5

php:7.2

 thrift -version :Thrift version 0.11.0

 

thrift文件模板:testServer.thrift

namespace php Rpc.Test


service Echop {
   string Echop(1: string str) ,
}

  

生成RPC文件:

thrift -r --out ./app --gen php:server ./ThriftSource/testServer.thrift

  

thrift之php,python使用TServerSocket并发 处理请求

 

服务端的实现:

安装第三方扩展包:

composer require sunlong/thrift

或者

https://github.com/sunlongv5/thrift.git

composer文件修改:

"autoload": {
        "classmap": [
            "app/Rpc"

        ],
        "psr-4": {
            "Rpc\\": "app/Rpc",
            "Services\\": "app/services",
            "Thrift\\": "vendor/sunlong/thrift/lib/php/lib/Thrift/"
        }
    },

  

  

新建Sevice文件夹创建文件EchopServie.php  实现thrift的Echop方法

<?php
namespace Services;
use Rpc\Test\EchopIf;

class EchopServie implements EchopIf{
    public function Echop($str){
        \Log::info($str);
        sleep(5);
        return "RPC:".$str;
    }
}

  

  

创建文件app\Console\Commands\RpcServer.php

此代码为thrift的server实现

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Thrift\Exception\TException;
use Thrift\Factory\TBinaryProtocolFactory;
use Thrift\Factory\TTransportFactory;
use Thrift\Server\TServerSocket;
use Thrift\Server\TSimpleServer;
use Thrift\Server\TForkingServer;
use Thrift\TMultiplexedProcessor;
use Rpc\Test\EchopClient;
use Rpc\Test\EchopProcessor;
use Thrift\Protocol\TBinaryProtocol;
use Thrift\Transport\TBufferedTransport;


class RpcServer extends Command{
    protected $signature = 'server:rpc';

    /**
     * 控制台命令说明。
     *
     * @var string
     */
    protected $description = 'rpc 服务';

    protected static $socketController;


    public function handle()
    {
        try {

            $handler = new \Services\EchopServie();
            $processor = new EchopProcessor($handler);
            // 将服务注册到TMultiplexedProcessor中
            $tFactory = new TTransportFactory();
            $pFactory = new TBinaryProtocolFactory(true, true);
            $multiplexedProcessor = new TMultiplexedProcessor();
            $multiplexedProcessor->registerProcessor("Echop", $processor);
            // 监听开始
            $transport = new TServerSocket('0.0.0.0', '9998');
            $server = new TForkingServer($processor, $transport, $tFactory, $tFactory, $pFactory, $pFactory);
            $server->serve();
        } catch (TException $te) {
            throw new \Exception($te->getMessage());
        }
    }





}
RpcServer

相关文章: