Nginx监控请求lua脚本

当应答状态码不是200时,通过udp向服务器发送报告。

monitor.lua

-- 
-- Config Nginx.conf:
--
-- set $str $uri;
-- content_by_lua_file;
-- 
-- location /proxy {
--    proxy_pass http://{your-server}$str;
-- }
--

--
-- Extends int to 4 byte
--
function pad32bit(num)
    local hex = ""
    local rem = num
    for i=1,4 do
      local bit = rem % 256
      rem = math.floor(rem /256)

      hex = hex .. string.char(bit)
    end
    return hex
end

local url = ngx.var.uri
local res = ngx.location.capture("/proxy", {vars = {str = url} })

-- Response
ngx.say(res.body)

-- Send udp message
if res.status ~= 200 then

-- Protocol
-- Length | version | Top-Level no (4) | Second-Level no | json body

  --local mydata = require "mydata"
  --local udpsock = mydata:socket()

  local udpsock = ngx.socket.udp()
  udpsock:settimeout(0)
  local ok, err = udpsock:setpeername("224.3.29.71", 10000)

  local body = "host:" .. ngx.var.host  .. ", url:" .. url .. ", status:" .. res.status
  local leng = 4 + 3 + string.len(body)

  local msg = pad32bit(leng) .. "\1\4\1" .. body

  ngx.say("<!--" .. msg .. "-->")

  local ok, err = udpsock:send(msg)

end

Nginx.conf

    upstream web{
         server 127.0.0.1:8080;
         server 127.0.0.1:8081;
    }

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        location / {
            root   html;
            index  index.html index.htm;

            set $str $uri;
            content_by_lua_file /home/hailin/monitor.lua;
        }

        location /proxy {
             resolver 8.8.8.8;

             proxy_pass http://web$str;
        }


  --local mydata = require "mydata"
  --local udpsock = mydata:socket()

这种方式只能共享基本类型,不能共享socket

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值