1. 程式人生 > 程式設計 >Nginx與Lua灰度釋出的實現

Nginx與Lua灰度釋出的實現

安裝 memcached

yum install -y memcached
#啟動memcached服務,埠11211,以nobody身份啟動,-d後臺模式執行
memcached -p11211 -u nobody -d
#將自己的IP設為灰度測試的IP
telnet 127.0.0.1 11211
set 119.32.216.122 0 0 1
1
quit

安裝 memcached for lua

wget https://github.com/openresty/lua-resty-memcached/archive/v0.11.tar.gz
tar -zxvf v0.11.tar.gz
mkdir -p /usr/local/share/lua/5.1
cp -r lua-resty-memcached-0.11/lib/resty /usr/local/share/lua/5.1

建立 test.lua 檔案

clientIP=ngx.req.get_headers()["X-Real-IP"]
if clientIP == nil then
  clientIP=ngx.req.get_headers()["x_forwarded_for"]
end
if clientIP == nil then
  clientIP=ngx.var.remote_addr
end
  local memcached=require "resty.memcached"
  local memc,err=memcached:new()
  if not memc then
    ngx.say("failed to instantiate memc:",err)
    return
  end
  local ok,err =memc:connect("127.0.0.1",11211)
  if not ok then
    ngx.say("failed to connect:",err)
    return
  end
  local res,flags,err =memc:get(clientIP)
  --ngx.say("value key: ",res,clientIP)
  if err then
    ngx.say("failed to get clientIP",err)
    return
  end
  if res == "1" then
    ngx.exec("@server_test")
    return
  end
  ngx.exec("@server_product")

nginx配置

  server {
    listen 8867;
    server_name www.siguoya.name;
    root /usr/local/nginx/1.12.1/html;
    location / {
      content_by_lua_file /etc/nginx/test.lua;
    }
    location /hello {
      default_type text/plain;
      content_by_lua 'ngx.say("hello lua")';
    }
    location /ua {
      default_type text/plain;
      content_by_lua '
        clientIP=ngx.req.get_headers()["USER-AGENT"]
        ngx.say("IP:",clientIP)
        ';
    }
    location @server_product {
      default_type text/plain;
      return 200 'product';
    }
    location @server_test {
      default_type text/plain;
      return 200 'test';
    }
  }

由於我們將 119.32.216.122 這個IP新增進了memcached中,因此訪問 http://www.siguoya.name:8867/ 的時候,看到的內容就是 test

而開啟全域性代理之後,發現看到的內容就是 product,這樣就實現了針對部分使用者進行灰度測試的效果

到此這篇關於Nginx與Lua灰度釋出的實現的文章就介紹到這了,更多相關Nginx與Lua灰度釋出內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!