创建一个简单的http服务器。
1.创建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();
2.在终端运行命令行 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掉相应的进程号即可。
3.配置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处理业务逻辑层。