Swoole通过Ngnix转发搭建http服务器
swoole_http_server
swoole_http_server继承自swoole_server,用于创建swoole版的http服务器。php也可以自己创建http服务器了?对,你没听错,是http服务器。
所谓的http服务器,其含义就是一旦我们部署好,用户便可以直接通过浏览器访问该服务器。理论上而言,我们不需要再借用nginx或者httpd部署,是不是很神奇?但是,理论归理论,swoole_http_server对HTTP协议的支持还不成熟,所以实际,我们还是需要用nginx作为代理。
下面我们创建一个简单的http服务器。
-
创建http.php 文件
<?php $http = new swoole_http_server("127.0.0.1", 8000); $http->on('request', function (swoole_http_request $request, swoole_http_response $response) { $response->status(200); $response->end('hello world.'); }); $http->start();
-
在终端运行命令行
php http.php
开启http服务
如果报错WARNING swSocket_bind (ERROR 502): bind(0.0.0.0:9501) failed. Error: Address already in use [98]
自行通过netstat -apn | grep 8000
查看端口被占用情况。kill
掉相应的进程号即可。 -
配置Ngnix
即使swoole_http_server再牛逼,他现在也没赶超老牌的nginx,所以,在http请求上,我们还是靠nginx来处理,通过nginx把请求转发给swoole,如此一来你有没有发现整个逻辑少了fpm?没错,nginx+swoole顺利上位。下面我们配置一个域名叫 "swoole.example.com"的站看看。
首先我们把监听8000端口的swoole_http_server打开,然后nginx添加如下的配置,重启nginx后,我们访问下 swoole.example.com 看看结果。不要忘记配置host哦
server { listen 80; root /var/www/test/; server_name swoole.example.com; index index.php index.html; location / { if (!-e $request_filename) { proxy_pass http://127.0.0.1:8000; } } }
默认 /var/www/test/ 目录下我们没有任何文件,空目录,location中我们判断如果访问的文件不存在,就转发到本地的8000端口即swoole_http_server。
我们访问下 http://swoole.example.com/index.html ,index.html是不存在的,按照nginx的逻辑,这个请求会被转发到本地的8000端口,所以结果页面展示的是hello world. 没有问题。也就是说现在我们成功的使用了nginx代理,swoole处理业务逻辑层。