對于開發(fā)來說需要有好的生態(tài)開發(fā)庫來輔助我們快速開發(fā),而 Lua 中也有大多數(shù)我們需要的第三方開發(fā)庫如 Redis、Memcached、Mysql、Http 客戶端、JSON、模板引擎等。 一些常見的 Lua 庫可以在 github 上搜索,https://github.com/search?utf8=%E2%9C%93&q=lua+resty。
lua-resty-redis 是為基于 cosocket API 的 ngx_lua 提供的 Lua redis 客戶端,通過它可以完成 Redis 的操作。默認(rèn)安裝 OpenResty 時已經(jīng)自帶了該模塊,使用文檔可參考https://github.com/openresty/lua-resty-redis。
在測試之前請啟動 Redis 實例:
nohup /usr/servers/redis-2.8.19/src/redis-server/usr/servers/redis-2.8.19/redis_6660.conf &
編輯 test_redis_baisc.lua
Java 代碼
local function close_redis(red)
if not red then
return
end
local ok, err = red:close()
if not ok then
ngx.say("close redis error : ", err)
end
end
local redis = require("resty.redis")
--創(chuàng)建實例
local red = redis:new()
--設(shè)置超時(毫秒)
red:set_timeout(1000)
--建立連接
local ip = "127.0.0.1"
local port = 6660
local ok, err = red:connect(ip, port)
if not ok then
ngx.say("connect to redis error : ", err)
return close_redis(red)
end
--調(diào)用API進(jìn)行處理
ok, err = red:set("msg", "hello world")
if not ok then
ngx.say("set msg error : ", err)
return close_redis(red)
end
--調(diào)用API獲取數(shù)據(jù)
local resp, err = red:get("msg")
if not resp then
ngx.say("get msg error : ", err)
return close_reedis(red)
end
--得到的數(shù)據(jù)為空處理
if resp == ngx.null then
resp = '' --比如默認(rèn)值
end
ngx.say("msg : ", resp)
close_redis(red)
基本邏輯很簡單,要注意此處判斷是否為 nil,需要跟 ngx.null 比較。
example.conf 配置文件
Java 代碼
location /lua_redis_basic {
default_type 'text/html';
lua_code_cache on;
content_by_lua_file /usr/example/lua/test_redis_basic.lua;
}
訪問如 http://192.168.1.2/lua_redis_basic 進(jìn)行測試,正常情況得到如下信息
msg : hello world
建立 TCP 連接需要三次握手而釋放 TCP 連接需要四次握手,而這些往返時延僅需要一次,以后應(yīng)該復(fù)用 TCP 連接,此時就可以考慮使用連接池,即連接池可以復(fù)用連接。
我們只需要將之前的 close_redis 函數(shù)改造為如下即可:
Java 代碼
local function close_redis(red)
if not red then
return
end
--釋放連接(連接池實現(xiàn))
local pool_max_idle_time = 10000 --毫秒
local pool_size = 100 --連接池大小
local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
if not ok then
ngx.say("set keepalive error : ", err)
end
end
即設(shè)置空閑連接超時時間防止連接一直占用不釋放;設(shè)置連接池大小來復(fù)用連接。
此處假設(shè)調(diào)用 red:set_keepalive(),連接池大小通過 nginx.conf 中 http 部分的如下指令定義:
#默認(rèn)連接池大小,默認(rèn) 30 lua_socket_pool_size 30; #默認(rèn)超時時間,默認(rèn) 60s lua_socket_keepalive_timeout 60s;
注意:
pipeline 即管道,可以理解為把多個命令打包然后一起發(fā)送;MTU(Maxitum Transmission Unit 最大傳輸單元)為二層包大小,一般為 1500 字節(jié);而 MSS(Maximum Segment Size 最大報文分段大小)為四層包大小,其一般是 1500-20(IP 報頭)-20(TCP 報頭)=1460 字節(jié);因此假設(shè)我們執(zhí)行的多個 Redis 命令能在一個報文中傳輸?shù)脑?,可以減少網(wǎng)絡(luò)往返來提高速度。因此可以根據(jù)實際情況來選擇走 pipeline 模式將多個命令打包到一個報文發(fā)送然后接受響應(yīng),而 Redis 協(xié)議也能很簡單的識別和解決粘包。
修改之前的代碼片段
Java 代碼
red:init_pipeline()
red:set("msg1", "hello1")
red:set("msg2", "hello2")
red:get("msg1")
red:get("msg2")
local respTable, err = red:commit_pipeline()
--得到的數(shù)據(jù)為空處理
if respTable == ngx.null then
respTable = {} --比如默認(rèn)值
end
--結(jié)果是按照執(zhí)行順序返回的一個table
for i, v in ipairs(respTable) do
ngx.say("msg : ", v, "<br/>")
end
通過 init_pipeline() 初始化,然后通過 commit_pipieline() 打包提交 init_pipeline() 之后的Redis命令;返回結(jié)果是一個 lua table,可以通過 ipairs 循環(huán)獲取結(jié)果;
配置相應(yīng) location,測試得到的結(jié)果
msg : OK
msg : OK
msg : hello1
msg : hello2
Redis Lua 腳本
利用 Redis 單線程特性,可以通過在 Redis 中執(zhí)行 Lua 腳本實現(xiàn)一些原子操作。如之前的 red:get("msg") 可以通過如下兩種方式實現(xiàn):
1、直接 eval:
Java 代碼
local resp, err = red:eval("return redis.call('get', KEYS[1])", 1, "msg");
2、script load 然后 evalsha SHA1 校驗和,這樣可以節(jié)省腳本本身的服務(wù)器帶寬: Java 代碼
local sha1, err = red:script("load", "return redis.call('get', KEYS[1])");
if not sha1 then
ngx.say("load script error : ", err)
return close_redis(red)
end
ngx.say("sha1 : ", sha1, "<br/>")
local resp, err = red:evalsha(sha1, 1, "msg");
首先通過 script load 導(dǎo)入腳本并得到一個 sha1 校驗和(僅需第一次導(dǎo)入即可),然后通過evalsha 執(zhí)行 sha1 校驗和即可,這樣如果腳本很長通過這種方式可以減少帶寬的消耗。
此處僅介紹了最簡單的 redis lua 腳本,更復(fù)雜的請參考官方文檔學(xué)習(xí)使用。
另外 Redis 集群分片算法該客戶端沒有提供需要自己實現(xiàn),當(dāng)然可以考慮直接使用類似于Twemproxy 這種中間件實現(xiàn)。
Memcached 客戶端使用方式和本文類似,本文就不介紹了。
lua-resty-mysql 是為基于 cosocket API 的 ngx_lua 提供的 Lua Mysql 客戶端,通過它可以完成 Mysql 的操作。默認(rèn)安裝 OpenResty 時已經(jīng)自帶了該模塊,使用文檔可參考https://github.com/openresty/lua-resty-mysql。
Java 代碼
local function close_db(db)
if not db then
return
end
db:close()
end
local mysql = require("resty.mysql")
--創(chuàng)建實例
local db, err = mysql:new()
if not db then
ngx.say("new mysql error : ", err)
return
end
--設(shè)置超時時間(毫秒)
db:set_timeout(1000)
local props = {
host = "127.0.0.1",
port = 3306,
database = "mysql",
user = "root",
password = "123456"
}
local res, err, errno, sqlstate = db:connect(props)
if not res then
ngx.say("connect to mysql error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)
return close_db(db)
end
--刪除表
local drop_table_sql = "drop table if exists test"
res, err, errno, sqlstate = db:query(drop_table_sql)
if not res then
ngx.say("drop table error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)
return close_db(db)
end
--創(chuàng)建表
local create_table_sql = "create table test(id int primary key auto_increment, ch varchar(100))"
res, err, errno, sqlstate = db:query(create_table_sql)
if not res then
ngx.say("create table error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)
return close_db(db)
end
--插入
local insert_sql = "insert into test (ch) values('hello')"
res, err, errno, sqlstate = db:query(insert_sql)
if not res then
ngx.say("insert error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)
return close_db(db)
end
res, err, errno, sqlstate = db:query(insert_sql)
ngx.say("insert rows : ", res.affected_rows, " , id : ", res.insert_id, "<br/>")
--更新
local update_sql = "update test set ch = 'hello2' where id =" .. res.insert_id
res, err, errno, sqlstate = db:query(update_sql)
if not res then
ngx.say("update error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)
return close_db(db)
end
ngx.say("update rows : ", res.affected_rows, "<br/>")
--查詢
local select_sql = "select id, ch from test"
res, err, errno, sqlstate = db:query(select_sql)
if not res then
ngx.say("select error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)
return close_db(db)
end
for i, row in ipairs(res) do
for name, value in pairs(row) do
ngx.say("select row ", i, " : ", name, " = ", value, "<br/>")
end
end
ngx.say("<br/>")
--防止sql注入
local ch_param = ngx.req.get_uri_args()["ch"] or ''
--使用ngx.quote_sql_str防止sql注入
local query_sql = "select id, ch from test where ch = " .. ngx.quote_sql_str(ch_param)
res, err, errno, sqlstate = db:query(query_sql)
if not res then
ngx.say("select error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)
return close_db(db)
end
for i, row in ipairs(res) do
for name, value in pairs(row) do
ngx.say("select row ", i, " : ", name, " = ", value, "<br/>")
end
end
--刪除
local delete_sql = "delete from test"
res, err, errno, sqlstate = db:query(delete_sql)
if not res then
ngx.say("delete error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)
return close_db(db)
end
ngx.say("delete rows : ", res.affected_rows, "<br/>")
close_db(db)
對于新增/修改/刪除會返回如下格式的響應(yīng):
Java 代碼
{
insert_id = 0,
server_status = 2,
warning_count = 1,
affected_rows = 32,
message = nil
}
affected_rows 表示操作影響的行數(shù),insert_id 是在使用自增序列時產(chǎn)生的 id。
對于查詢會返回如下格式的響應(yīng):
Java 代碼
{
{ id= 1, ch= "hello"},
{ id= 2, ch= "hello2"}
}
null 將返回 ngx.null。
Java 代碼
location /lua_mysql {
default_type 'text/html';
lua_code_cache on;
content_by_lua_file /usr/example/lua/test_mysql.lua;
}
http://192.168.1.2/lua_mysql?ch=hello 進(jìn)行測試,得到如下結(jié)果Java 代碼
insert rows : 1 , id : 2
update rows : 1
select row 1 : ch = hello
select row 1 : id = 1
select row 2 : ch = hello2
select row 2 : id = 2
select row 1 : ch = hello
select row 1 : id = 1
delete rows : 2
客戶端目前還沒有提供預(yù)編譯 SQL 支持(即占位符替換位置變量),這樣在入?yún)r記得使用 ngx.quote_sql_str 進(jìn)行字符串轉(zhuǎn)義,防止 sql 注入;連接池和之前 Redis 客戶端完全一樣就不介紹了。
對于 Mysql 客戶端的介紹基本夠用了,更多請參考 https://github.com/openresty/lua-resty-mysql。
其他如 MongoDB 等數(shù)據(jù)庫的客戶端可以從 github 上查找使用。
OpenResty 默認(rèn)沒有提供 Http 客戶端,需要使用第三方提供;當(dāng)然我們可以通過 ngx.location.capture 去方式實現(xiàn),但是有一些限制,后邊我們再做介紹。
我們可以從 github 上搜索相應(yīng)的客戶端,比如 https://github.com/pintsized/lua-resty-http。
Java 代碼
cd /usr/example/lualib/resty/
wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http_headers.lua
wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http.lua
Java 代碼
local http = require("resty.http")
--創(chuàng)建http客戶端實例
local httpc = http.new()
local resp, err = httpc:request_uri("http://s.taobao.com", {
method = "GET",
path = "/search?q=hello",
headers = {
["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36"
}
})
if not resp then
ngx.say("request error :", err)
return
end
--獲取狀態(tài)碼
ngx.status = resp.status
--獲取響應(yīng)頭
for k, v in pairs(resp.headers) do
if k ~= "Transfer-Encoding" and k ~= "Connection" then
ngx.header[k] = v
end
end
--響應(yīng)體
ngx.say(resp.body)
httpc:close()
響應(yīng)頭中的 Transfer-Encoding 和 Connection 可以忽略,因為這個數(shù)據(jù)是當(dāng)前 server 輸出的。
Java 代碼
location /lua_http_1 {
default_type 'text/html';
lua_code_cache on;
content_by_lua_file /usr/example/lua/test_http_1.lua;
}
Java 代碼
resolver 8.8.8.8;
記得要配置 DNS 解析器 resolver 8.8.8.8,否則域名是無法解析的。
http://192.168.1.2/lua_http_1 會看到淘寶的搜索界面。使用方式比較簡單,如超時和連接池設(shè)置和之前 Redis 客戶端一樣,不再闡述。更多客戶端使用規(guī)則請參考 https://github.com/pintsized/lua-resty-http。
ngx.location.capture 也可以用來完成 http 請求,但是它只能請求到相對于當(dāng)前 nginx 服務(wù)器的路徑,不能使用之前的絕對路徑進(jìn)行訪問,但是我們可以配合 nginx upstream 實現(xiàn)我們想要的功能。
Java 代碼
upstream backend {
server s.taobao.com;
keepalive 100;
}
即我們將請求 upstream 到 backend;另外記得一定要添加之前的 DNS 解析器。
Java 代碼
location ~ /proxy/(.*) {
internal;
proxy_pass http://backend/$1$is_args$args;
}
internal 表示只能內(nèi)部訪問,即外部無法通過 url 訪問進(jìn)來; 并通過 proxy_pass 將請求轉(zhuǎn)發(fā)到 upstream。
Java 代碼
local resp = ngx.location.capture("/proxy/search", {
method = ngx.HTTP_GET,
args = {q = "hello"}
})
if not resp then
ngx.say("request error :", err)
return
end
ngx.log(ngx.ERR, tostring(resp.status))
--獲取狀態(tài)碼
ngx.status = resp.status
--獲取響應(yīng)頭
for k, v in pairs(resp.header) do
if k ~= "Transfer-Encoding" and k ~= "Connection" then
ngx.header[k] = v
end
end
--響應(yīng)體
if resp.body then
ngx.say(resp.body)
end
通過 ngx.location.capture 發(fā)送一個子請求,此處因為是子請求,所有請求頭繼承自當(dāng)前請求,還有如 ngx.ctx和ngx.var 是否繼承可以參考官方文檔 http://wiki.nginx.org/HttpLuaModule#ngx.location.capture。 另外還提供了 ngx.location.capture_multi用于并發(fā)發(fā)出多個請求,這樣總的響應(yīng)時間是最慢的一個,批量調(diào)用時有用。
Java 代碼
location /lua_http_2 {
default_type 'text/html';
lua_code_cache on;
content_by_lua_file /usr/example/lua/test_http_2.lua;
}
http://192.168.1.2/lua_http_2 進(jìn)行測試可以看到淘寶搜索界面。我們通過 upstream+ngx.location.capture 方式雖然麻煩點,但是得到更好的性能和upstream 的連接池、負(fù)載均衡、故障轉(zhuǎn)移、proxy cache 等特性。
不過因為繼承在當(dāng)前請求的請求頭,所以可能會存在一些問題,比較常見的就是 gzip 壓縮問題,ngx.location.capture 不會解壓縮后端服務(wù)器的 GZIP 內(nèi)容,解決辦法可以參考https://github.com/openresty/lua-nginx-module/issues/12;因為我們大部分這種http 調(diào)用的都是內(nèi)部服務(wù),因此完全可以在 proxy location 中添加proxy_pass_request_headers off; 來不傳遞請求頭。