求助, 在 content_by_lua 里面拿到的ngx.var.body_bytes_sent 始终为零, flush 也不行

152 views
Skip to first unread message

zh...@wandoujia.com

unread,
Mar 12, 2014, 4:31:17 AM3/12/14
to open...@googlegroups.com
我使用ngx_openresty-1.5.8.1
想在 nginx 代理集群里面做一个proxy 的流量统计的功能, 数据写入到 redis.

因为 redis 无法在 log_by_lua 中使用, 所以我写了个 content_by_lua的redis脚本:
local redis = require "resty.redis"

local cache = redis.new()
local ok, err = cache.connect(cache, '10.0.25.74', '6379')

cache:select(30)
cache:set_timeout(60000)

if not ok then
return
end

ngx.flush()
local size = ngx.var.body_bytes_sent
local key = ngx.var.arg_user

res, err = cache:incrby(key, size)
cache:set(key..":bytes_sent", size)


nginx配置如下:
location ~* ^/proxy$ {
set_unescape_uri $rurl $arg_url;
if ($arg_url ~ ^http%3A%2F%2F(.+?)%2F(.*)$) {
set_unescape_uri $rpath $1;
}

resolver 8.8.8.8;
proxy_redirect off;
proxy_pass_header Server;
proxy_set_header Host $rpath;
proxy_set_header X-Real_IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_pass $rurl;

content_by_lua_file 'conf/redis.lua';
}

Yichun Zhang (agentzh)

unread,
Mar 12, 2014, 5:26:14 PM3/12/14
to openresty
Hello!

On Wed, Mar 12, 2014 at 1:31 AM, zhida wrote:
> resolver 8.8.8.8;
> proxy_redirect off;
> proxy_pass_header Server;
> proxy_set_header Host $rpath;
> proxy_set_header X-Real_IP $remote_addr;
> proxy_set_header X-Scheme $scheme;
> proxy_pass $rurl;
>
> content_by_lua_file 'conf/redis.lua';

你这里犯了初学者常犯的一种错误,即在一个 location {} 里面同时配置了两个 nginx 模块的 content handler.
这里,proxy_pass 注册了一个 content handler,而 content_by_lua 又注册了一个 content
handler,其结果是只有一个模块胜出,即只有 proxy_pass 运行,或者只有 content_by_lua 运行。

你这里应当使用 log_by_lua. 虽然 log_by_lua 的上下文里不能直接使用 cosocket,但你可以在
log_by_lua 里使用 ngx.timer.at() 创建 0 延时的定时器。在 timer 回调函数的上下文里,你可以使用
lua-resty-redis 这样的库。不过,建议你不要每次请求都触发一次 redis 写操作,因为那样开销比较大,建议你自己在 Lua
空间里自己进行缓存,然后按批把数据推送到 redis 这样的远方 TCP 服务。可以参考支家乐的
lua-resty-logger-socket 库的实现:

https://github.com/cloudflare/lua-resty-logger-socket

另外,建议仔细阅读我的 NGINX 中文教程,以避免再犯类似上面那样的低级错误 :) 见

http://openresty.org/download/agentzh-nginx-tutorials-zhcn.html

Regards,
-agentzh
Reply all
Reply to author
Forward
0 new messages