streetlamp/tp-hprose-swoole

使用hprose构建兼容thinkphp的微服务拓展包

v1.0.0 2021-04-08 06:28 UTC

This package is not auto-updated.

Last update: 2024-04-19 16:55:45 UTC


README

Packagist License

简介

tp-hprose-swoole基于Hprose构建的,需要结合ThinkPHP5.0来使用,简单构建分布式系统。

安装

通过 composer

{
     "require": {
            "streetlamp/tp-hprose-swoole": "dev-master"
     }
}

使用

你首先需要安装 swooleswoole 被支持的最低版本为 1.8.8.

一、配置说明

配置文件streetlamp_server.php,通过composer安装完之后,把该配置文件复制到tp框架的extra文件夹下面即可。 代码说明,文件路径application/extra/streetlamp_server.php

<?php
return [
    'streetlamp' => [               //服务名可配置多个服务
        'module'      => 'script',  //模块名。只有在模块的logic下的类才会被部署为微服务
        'host'        => '0.0.0.0', //ip
        'port'        => 9001,      //端口
        'server_type' => 'swoole',  //swoole socket两种
        'setting'     => [          //swoole的tcp服务配置可参考swoole文档
            'worker_num'  => 1,
            'max_request' => 5000,
            'daemonize'   => false,
            'log_file'    => LOG_PATH . 'streetlamp/log.log'
        ],
        'middlewares' => [          //Hprose的中间件配置
            //            \app\script\middleware\TestaMiddleware::class,
            //            \app\script\middleware\TestMiddleware::class,
        ]
    ],
    ...
];

二、注解

我们自定义了两个注解类Streetlamp\annotation\Mapping\Service和Streetlamp\annotation\Mapping\ServiceMethod。

1、Streetlamp\annotation\Mapping\Service注解只能应用在类上,在tp框架的每个模块文件夹下的logic文件夹下面的类,只有被这个注解修饰过的类才会被注册到微服务中。
2、Streetlamp\annotation\Mapping\ServiceMethod注解只能应用在类方法上,有个参数service_Name是必填的,用来定义方法名在服务中是惟一的。只有被这两个注解修饰过的类下的方法才会被注册到服务中。

代码说明,文件路径application/script/logic/Test.php

<?php
namespace app\script\logic;

use app\script\model\ProjectOrder;
use Streetlamp\annotation\Mapping\Service;
use Streetlamp\annotation\Mapping\ServiceMethod;

/**
 * Class Test
 * @package app\script\logic
 * @Service ()
 */
class Test
{
    /**
     * @ServiceMethod(serviceName="hello")
     */
    public function hello()
    {
        $channel = new \Swoole\Coroutine\Channel(1024);
        go(function () use ($channel) {
            try {
                $result = ProjectOrder::field('id')->select()->toArray();
            } catch (\Exception $e) {
                $result = $e;
            }
            $channel->push($result);
        });
        //挂起当前协程,等待所有任务完成后恢复
        $result = $channel->pop();
        if ($result instanceof \Exception)
            throw $result;
        return json_encode(['code' => 200, 'connection1' => $result]);

    }
}

三、中间件

中间件需要继承Streetlamp\Middleware并实现before和after这两个方法。before方法就是在执行服务方法前执行的逻辑内容,after方法就是在执行服务方法后执行的逻辑内容。 只有在配置文件streetlamp_server.php中注册了的中间件才会被应用到对应的服务中。

代码说明,文件路径application/script/middleware/TestaMiddleware.php

<?php
namespace app\script\middleware;
use Streetlamp\Middleware;
class TestaMiddleware extends Middleware
{
    public function before($name, &$args, \stdClass $context)
    {
        dump('执行前a');
    }

    public function after($name, &$args, \stdClass $context)
    {
        dump('执行后a');
    }
}

四、启动服务

利用ThinkPHP框架的自定义命令行功能在CLI模式下调用Streetlamp\Server的run方法即可启动微服务,实例化是传入配置文件中所定义的模块名即可。

代码说明,文件路径application/script/HproseServer.php

<?php
namespace app\script;
use app\library\exception\BaseException;
use Streetlamp\Server;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class HproseServer extends Command
{

    protected function configure()
    {
        $this->setName('hproseServer:start')->setDescription('hprose服务器');
    }

    public function execute(Input $input, Output $output)
    {
       (new Server('streetlamp'))->run();
    }
}

五、客户端调用

可参考Hprose for PHP用户手册

<?php
namespace app\index\controller;
use Hprose\Client;
use think\Controller;

class Index extends Controller
{
    public function index()
    {
        try {
            $client = Client::create('tcp://127.0.0.1:9001', false);
            $client->setIdempotent(true);
            $client->setRetry(5);
            $client->hello1()//hello1就是注解Streetlamp\annotation\Mapping\ServiceMethod参数serviceName的值
        } catch (\Exception $e) {
           throw $e;
        }

    }
}