laravel安装tars扩展

下载laravel项目:

创建Tars项目目录结构(scripts、src、tars),Laravel/Lumen项目放在src目录下

composer create-project laravel/laravel src --prefer-dist "5.5.*"

 

安装Laravel Tars包

更新Composer依赖

composer require "luoxiaojun1992/laravel-tars:*"

  添加ServiceProvider,编辑src/bootstrap/app.php

$app->register(\Lxj\Laravel\Tars\ServiceProvider::class);

 配置tcp服务端

在/tars目录自行撰写了一份tars文件,姑且命名为oms.tars

module OmsService
{
    interface OmsService
    {
        int route(string ControllerFunction,string Params, out string Response); // out代表输出参数,客户端可以获取到这个输出参数
    };

};

 修改配置文件/src/config/tars.php

 

初始化Laravel Tars

php artisan vendor:publish --tag=tars

执行

cd scripts && ./tars2php.sh

 

 生成 tars 相关代码

实现 tars 接口,创建src\app\Tars\impl\OmsServiceImpl.php

<?php

namespace App\Tars\impl;
use App\Tars\servant\hlyun\oms\tarsObj\OmsServiceServant;


class OmsServiceImpl implements OmsServiceServant
{


    /**
     * OmsServiceImpl constructor.
     */
    public function __construct()
    {
    }

    public function route($ControllerFunction,$Params,&$Response)
    {
        
        try {
            $ControllerFunction=explode('@', $ControllerFunction);
            $Response= call_user_func([new $ControllerFunction[0], $ControllerFunction[1]], $Params);
            $ResponseType=gettype($Response);
            if ($ResponseType!=='string') {
                $Response=json_encode(['code'=>502,'msg'=> "RPC接口返回数据类型必须为String,当前返回类型:".$ResponseType]);
            }
        } catch (\Exception $e) {
            $Response=json_encode(['code'=>502,'msg'=>'OmsServiceImpl@route 异常','getMessage' => $e->getMessage(), 'getFile' => $e->getFile(), 'getLine' => $e->getLine(), 'getTrace' => $e->getTraceAsString()],JSON_UNESCAPED_UNICODE);
        }

        return 0;
    }
    

}

 配置http客户端

 

修改/src/config/tars.php配置文件

 

 

初始化Laravel Tars

php artisan vendor:publish --tag=tars

复制服务端的oms.tars到客户端/tars目录下

执行

cd scripts && ./tars2php.sh

生成客户端调用代码

 

修改客户端调用文件,$_servantName改为对应服务端servantName

 

编写客户端调用代码

<?php

namespace App\Http\Controllers;

use Tars\client\CommunicatorConfig;
use Tars\App;

class IndexController extends TarsController
{
    public function actionIndex()
    {
        $config = new \Tars\client\CommunicatorConfig();
        $config->setLocator(\Tars\App::$tarsConfig['tars']['application']['client']['locator']);
        $config->setSocketMode(3);
        $config->setCharsetName('UTF-8');
        $omsService = new \App\Tars\servant\hlyun\gateway\httpObj\OmsServiceServant($config);
        $Response = '';
        $ControllerFunction='App\Http\Controllers\OmsController@index';
        $Params=[];
        $Params['ID']=1;
        $Params=json_encode($Params);
        $return = $omsService->route($ControllerFunction,$Params, $Response);
        return $Response;
  
    }
}

 

打包项目

 php artisan tars:deploy

 如果出现以下异常则在PHP模板添加对应参数

 

 

 

 

 重启服务

posted @ 2022-03-30 19:42  佚小名  阅读(95)  评论(0编辑  收藏  举报