Nginx的HTTP push模块可以实现长Polling。利用PHP管理频道的订阅和发布消息,这样就可以非常方便的实现聊天、即时信息等传递到客户端,并且不会增加PHP的进程数量。
1. 下载nginx http push module源代码,降压到/var/tmp中
2. 下来nginx的src.rpm包,安装后修改spec文件中的configure指令,增加:
--add-module=/var/tmp/nginx_http_push_module
3. rpmbuild nginx包,并安装
4. 配置nginx:
location /polling/ {
proxy_pass http://127.0.0.1:8080;
}
location /polling/sub/ {
internal;
set $push_channel_id $arg_id;
push_subscriber;
push_subscriber_concurrency broadcast;
push_channel_group broadcast;
}
location /polling/pub/ {
allow 127.0.0.1;
deny all;
set $push_channel_id $arg_id;
push_publisher;
push_min_message_buffer_length 5;
push_max_message_buffer_length 20;
push_message_timeout 2m;
push_channel_group broadcast;
}
5. PHP部分
在PHP中处理/polling/请求的GET和POST方法。
5.1 处理GET的时候判断客户的Cookie,如果已经有权限,则:
header("X-Accel-Redirect: /polling/sub/?".$_SERVER['QUERY_STRING']);
否则就去鉴权用户。
5.2 处理POST的时候判断客户是否有POST权限,如果有则发起HTTP POST调用,将数据完全转发给:
http://127.0.0.1/polling/pub/?$_SERVER['QUERY_STRING']
这样就综合利用了nginx的长POLLING功能和PHP的脚本管理优势。