本文摘自: https://segmentfault.com/p/1210000011625271/read
不采用lua之前,我們從redis獲取數據的路徑與采用lua之后獲取數據的路徑對比,明顯可以看出效率的提升。
安裝OpenResty
參考官方給出的yum安裝步驟,各種系統均有支持,也可采用源碼安裝的形式,安裝完成后默認路徑是/usr/local/openresty,新版本的OpenResty自帶Redis操作模塊,所以無須我們自己重新安裝。
配置nginx
在http模塊下面增加如下配置
lua_package_path "/usr/local/openresty/lualib/?.lua;;"; #lua 模塊
lua_package_cpath "/usr/local/openresty/lualib/?.so;;"; #c模塊
為更好的配置lua配置,獨立lua.conf文件,不與nginx.conf攪合一起, lua.con文件中配置如下:
#lua.conf
server {
listen 80;
server_name _;
}
在nginx.conf文件中http模塊將其引入
include lua.conf;
簡單測試
編寫簡單的lua腳本文件test.lua,存儲目錄位於conf/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獲取數據,大大提高的數據請求響應的效率。