需求:
通過URI地址http://10.0.0.148/test2?uuid=123的uuid參數值的第一位,去實現redis的負載均衡
若uuid第一位為1,那么去10.0.0.148的redis,若uuid第一位為2,那么去10.0.0.248的redis
測試的時候148的redis里給foo賦值kkk(./redis-cli set foo kkk),248的不賦值
這里10.0.0.148既是nginx服務器,也是redis服務器
方法一:通過加載lua文件的方式
test2.lua
--使用require來加載模塊名-- local redis = require "resty.redis" --創建一個對象-- local cache = redis.new() --獲取URI里的參數uuid local arg = ngx.var.arg_uuid --截取參數值的第一個字符 local uuid_f = string.sub(arg,0,1) --將第一個參數值轉換為整形 uuid_f=tonumber(uuid_f) --通過列表定義redis的IP local numbers = {[1]="10.0.0.148",[2]="10.0.0.248"} --根據uuid的不同參數值去連接不同的redis服務器 local ok,err = cache.connect(cache,numbers[uuid_f],'6379') --判斷是否能連接上 if not ok then ngx.say("failed to connect:",err) return end --測試獲取redis的foo變量的值 local res = cache:get("foo")
if res==ngx.null then ngx.say("This is null") else ngx.say(res) end cache:close()
在nginx.conf中添加如下配置:
location /test2 { default_type text_plain; content_by_lua_file /usr/local/test2.lua; }
測試結果:


#user nobody; worker_processes 1; #pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; init_by_lua ' redis = require "resty.redis" numbers = {["0"]="10.0.0.148",["1"]="10.0.0.248"} '; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } location /echo { default_type text/plain; echo hello lua; } location /test { default_type text_plain; content_by_lua 'ngx.say("Hi lile")'; } location /re { default_type text_plain; content_by_lua ' local headers = ngx.req.get_headers() local ip = headers["X-REAL-IP"] or headers["X_FORWARDED_FOR"] or ngx.var.remote_addr or "0.0.0.0" ngx.say(ip.."#"..os.time().."000") '; } location /test2 { #default_type application/json; default_type text_plain; content_by_lua ' local redis_client = redis.new() local arg = ngx.var.arg_uuid local uuid_f = string.sub(arg,0,1) local ok,err=redis_client.connect(redis_client,numbers[uuid_f],"6379") if not ok then ngx.say("failed to connect:",err) return end local res = redis_client:get("foo") if res==ngx.null then ngx.say("This is null") else ngx.say(res) end redis_client:close() '; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
總結:
從昨天開始弄這個的時候,完全沒接觸過啊,redis 是數據庫都不知道,只知道這個名字,lua也是第一次聽啊,nginx一直想好好研究一下,但是都沒行動過,然后就使勁的在網上找資料,發現基本上都一樣,弄的很復雜很復雜,今天早上來,不知道為啥,突然就大腦很清醒,想的很簡單,沒想到反而這樣可以,可能是昨晚睡得比較好,精神也好,最近被達康書記給迷倒了,每天熬夜追劇,話說真的睡眠真的可以讓你精神倍兒好,心情也會好。nginx通過lua,根據自己的規則去訪問redis服務器,首先我肯定得用lua實現nginx與redis的連接,所以就有那個加載模塊,創建對象,連接這幾個步驟,這相當於只有你想連上redis,你就得這么做,然后我要根據參數來定規則,我肯定得獲取這個參數的值,然后進行轉換....當然,這只是事后的想法,現在都不相信我居然弄了這個,雖然過兩天,這些又忘了,但是至少我知道有這個東西,知道怎么分析問題,而不是一個勁的去搜怎么做。