tp5.1 用swoole扩展,快速编写抗高并发接口以及路由设置。

1.开启swoole服务器。

namespace app\index\controller;

class Swoole extends \think\swoole\Server
{
    protected static $token;
    protected $host = '0.0.0.0';
    protected $port = 9501;
    protected $serverType = 'http';
    protected static $uid = '';
    protected $option = [
        'worker_num' => 4, // 设置启动的Worker进程数
        // 'daemonize' => true, //守护进程化。
        //'backlog' => 128, //Listen队列长度,
        //'dispatch_mode' => 2,
    ];


    public function onStart($server)
    {
        echo 'http_start';
    }

    public function onRequest($req, $response)
    {
        $response->header("Content-Type", "text/html; charset=utf-8");
        try {
            $url = isset(Route::config()[($req->server)['request_uri']]) ? Route::config()[($req->server)['request_uri']] : '';
            if($url == '') return $response->end('路由不正确');
            if($url[0] != '' &&  $url[0] != ($req->server)['request_method']) return $response->end('请求方式不正确');
            $action = $url[2];
            return $response->end(json_encode((new $url[1])->$action($req),JSON_UNESCAPED_UNICODE));
        } catch (\Exception $e) {
            return $response->end($e->getMessage());
        }
    }

}

命令:没有报错,打印出 “http_start” 就成功了,不要忘记启用 端口。 

# 终端 /public 下执行
php index.php index/Swoole/start

2,路由设置

namespace app\index\controller;

use think\Controller;

class Route extends Controller
{
    static public function config() {
        return [
            '/index/index/test'=>['GET',Index::class,'test']
        ];
    }
}

3,接口编写

namespace app\index\controller;

use think\cache\driver\Redis;
use think\Controller;
use think\Db;

class Index extends Controller
{
    private $red = '';

    public function _initialize()
    {
        $this->red = redis();
    }

    public function test($req)
    {
        $redis = new \think\cache\driver\Redis(['password' => 'siye3172806']);
        $this->red = $redis;
        //get 参数
        $id = ($req->get)['id'];
        //Db::name('user')->insert(['v'=>time()]);
        $res = $this->red->get($id);
        if(!$res) {
            $res = Db::name('user')->where('id',$id)->find();
            $this->red->set($id,$res,30);
        }
        //dump($res);
        return ['status'=>1,'msg'=>'成功','data'=>$res];
        //return $req['get']['id'];
    }
}

 

访问地址 :

http://<地址>:9501/index/index/test2?id=123

地址加端口可以用nginx反向代理,加域名。但会影响性能。

纯静态接口

测试 设置 -n100 -c100

地址加端口的方式:  并发在1500以上

nginx反向代理的方式:  并发在1000左右

原生php惨不忍睹 30 多

 

 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值