使用openresty+redis轻松实现网站访问统计
网站的受访统计是网站运营和优化的一个重要参考数据,对于并发量较大的网站,我们可以通过nginx+redis的架构来简单实现页面受访统计。这主要得益于nginx的高并发性能和redis快速存取内存数据。实际应用中,我们可以使用openresty来快速搭建统计系统。
openresty集合了lua和lua-redis访问库,可以通过编写nginx.conf配置文件实现对redis数据库的存取。简单且高效。
- 安装和配置openresty及redis
- 修改nginx.conf,示例:
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;server {
listen 8088;
server_name www.test.com;location /get_pv {
set $id_param $args;
content_by_lua ‘
local redis_mod = require “resty.redis”
local redis_db= redis_mod:new()
redis_db:set_timeout(1000) — 1 secondlocal ok, err = redis_db:connect(“127.0.0.1”, 6379)
if not ok then
ngx.log(ngx.ERR, “failed to connect to redis: “, err)
return ngx.exit(500)
endlocal id = string.sub(ngx.var.id_param, 4)
local pv, err = redis_db:get(id)
if not pv then
redis_db:close()
ngx.log(ngx.ERR, “failed to get redis key: “, id, err)
return ngx.exit(500)
endif pv == ngx.null then
redis_db:close()
ngx.log(ngx.ERR, “no pv found for “, id)
return ngx.exit(400)
endredis_db:close()
ngx.header.content_type = “text/plain”;
ngx.say(pv)
‘;
}
}server {
listen 9099;
server_name www.test.com;location /set_pv {
set $id_param $args;
content_by_lua ‘
local redis_mod = require “resty.redis”
local redis_db= redis_mod:new()
redis_db:set_timeout(1000) — 1 secondlocal ok, err = redis_db:connect(“127.0.0.1”, 6379)
if not ok then
ngx.log(ngx.ERR, “failed to connect to redis: “, err)
return ngx.exit(500)
endlocal id = string.sub(ngx.var.id_param, 4)
local pv = redis_db:incr(id)
if not pv then
redis_db:close()
ngx.log(ngx.ERR, “failed to incr redis key: “, id, err)
return ngx.exit(500)
endredis_db:close()
ngx.header.content_type = “text/plain”;
ngx.say(pv)
‘;
}
}
} - 在网站页面中部署统计代码
<iframe frameborder=”0″ scrolling=”no” width=”0″ height=”0″ style=”display:none;” src=”http://www.test.com:9099/set_pv?id=page_411“></iframe>