Lua与redis结合应用于nginx的动态upstream

技术要求很简明:

nginx分发请求的时候,upstream是由lua从redis中读取配置动态生成的,这样便于用程序动态修改。

装好nginx+lua,过程不表。 把lua redis的模块配到路径中

1wget https://raw.github.com/nrk/redis-lua/version-2.0/src/redis.lua  

nginx配置如下:

 1server {  
 2  listen 80;
 3  server_name _;
 4  server_name_in_redirect off;
 5  port_in_redirect off;
 6  root /root/html;
 7
 8  location / {
 9    set $upstream "";
10    rewrite_by_lua '
11      -- load global route cache into current request scope
12      -- by default vars are not shared between requests
13      local routes = _G.routes
14
15      -- setup routes cache if empty
16      if routes == nil then
17        routes = {}
18        ngx.log(ngx.ALERT, "Route cache is empty.")
19      end
20
21      -- try cached route first
22      local route = routes[ngx.var.http_host]
23      if route == nil then
24        local redis  = require "redis"
25        local client = redis.connect("localhost", 6379)
26        route        = client:get(ngx.var.http_host)
27      end
28
29      -- fallback to redis for lookups
30      if route ~= nil then
31        ngx.var.upstream = route
32        routes[ngx.var.http_host] = route
33        _G.routes = routes
34      else
35        ngx.exit(ngx.HTTP_NOT_FOUND)
36      end
37    ';
38
39    proxy_buffering             off;
40    proxy_set_header            Host $host;
41    proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;
42    proxy_redirect              off;
43    proxy_connect_timeout       10;
44    proxy_send_timeout          30;
45    proxy_read_timeout          30;
46    proxy_pass                  http://$upstream;
47  }
48}

送进redis一些数据

1redis-cli =>  
2SET localhost 127.0.0.1:49153  

测试一下:

1curl -i -X HEAD "http://127.0.0.1/" # -> 404,没这个域名  
2curl -i -X HEAD "http://localhost/" # -> 正常  

Kvm的虚机中如何在线挂接一块新网卡
Nginx下lua根据客户端ip进行分发
comments powered by Disqus