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 多