Nginx+Lua+Redis 實現高性能緩存數據讀取

本文摘自: https://segmentfault.com/p/1210000011625271/readhtml

不採用lua以前,咱們從redis獲取數據的路徑與採用lua以後獲取數據的路徑對比,明顯能夠看出效率的提高。nginx

 

 

 

安裝OpenResty

參考官方給出的yum安裝步驟,各類系統均有支持,也可採用源碼安裝的形式,安裝完成後默認路徑是/usr/local/openresty,新版本的OpenResty自帶Redis操做模塊,因此無須咱們本身從新安裝。redis

配置nginx

在http模塊下面增長以下配置json

lua_package_path "/usr/local/openresty/lualib/?.lua;;"; #lua 模塊
lua_package_cpath "/usr/local/openresty/lualib/?.so;;"; #c模塊segmentfault

爲更好的配置lua配置,獨立lua.conf文件,不與nginx.conf攪合一塊兒, lua.con文件中配置以下:瀏覽器

#lua.conf
server {
listen 80;
server_name _;
}測試

在nginx.conf文件中http模塊將其引入ui

include lua.conf;this

簡單測試

編寫簡單的lua腳本文件test.lua,存儲目錄位於conf/lua下面lua

ngx.say("hello lua world");

修改lua.conf

location /lua {
default_type 'text/html'; 

lua_code_cache off; 

content_by_lua_file conf/lua/test.lua;
}

測試配置是否正確

./nginx -t #檢測配置文件是否正確 , 顯示以下日誌即表示成功

nginx: [alert] lua_code_cache is off; this will hurt performance in/usr/local/nginx/conf/lua.conf:7
nginx: [alert] lua_code_cache is off; this will hurt performance in/usr/local/nginx/conf/lua.conf:13
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

在瀏覽器輸入http://192.168.1.105/lua,頁面正常輸出「hello lua world 」

支持JSON

腳本地址 http://lua-users.org/wiki/JsonModules

正常的獲取string類型值沒有問題,在咱們獲取json格式的key值就須要JSON的支持才能正常顯示。下載腳本將其放置在/usr/local/openresty/lualib目錄下面,以便在lua腳本中引用

獲取redis數據

編寫鏈接redis的測試腳本,並從redis中獲取指定key的值。腳本內容以下:

local redis = require("resty.redis")
local json = require ("dkjson")

--建立實例
local redis_instance = redis:new()
--設置超時(毫秒)
redis_instance:set_timeout(3000)
--創建鏈接
local host = "127.0.0.1"
local port = 6679
local ok, err = redis_instance:connect(host, port)
if not ok then
ngx.say("connect to redis error : ", err)
return close_redis(redis_instance)
end
local resp, err = redis_instance:eval("return redis.call('get', KEYS[1])", 1, "alibaba");
ngx.say("redis data = ",resp);

ngx.say("redis data = ",resp); ngx.say("json data = ",json.encode(resp))

--正常狀況理應有關閉redis,這裏僅簡單測試下,未作關閉

配置lua.conf,內容以下

location /lua_redis_test {
default_type 'text/html';
lua_code_cache off;
content_by_lua_file /usr/local/nginx/conf/lua/json_test.lua;
}

向redis中寫入alibaba鍵的值,這裏使用jedis簡單寫入便可

Jedis redis = new Jedis("192.168.1.105", 6679); 

JSONObject object = new JSONObject(); 

object.put("aaaa", 123); 

object.put("bbbbb", 23234); 

redis.set("alibaba", object.toString());

測試配置無誤後,重啓nginx。瀏覽器輸入http://192.168.1.105/lua_redis_test,應當輸出redis中alibaba鍵的值。

redis data = {"aaaa":123,"bbbbb":23234}json data = "{"aaaa":123,"bbbbb":23234}

至此基於nginx,經過lua腳本便可簡單從redis獲取數據,大大提升的數據請求響應的效率。

相關文章
相關標籤/搜索