Nginx+Lua 积累

时间:2023-03-09 22:29:10
Nginx+Lua 积累

1、解析16进制编码的中文参数

local encodeStr = "%E6%B0%94"
local decodeStr = "";
for i = , #encodeStr - , do
local num = encodeStr:sub(i, i + );
num = tonumber(num, );
decodeStr = decodeStr .. string.char(num);
end
ngx.say(decodeStr)

2、类似replace

local str = "a1b1c1d"
local result = string.gsub(str,"","") --将1替换成2 local str = "A1B1C1"
local result = string.gsub(str,"1","0",2) --输出的结果为:A0B0C1

3、直连mysql

local mysql = require "resty.mysql"
local db = mysql:new()
db:connect{
host = "10.10.3.218",
port = ,
database = "test_db",
user = "root",
password = "",
max_packet_size = *
}
local result = db:query("SELECT ID,NAME FROM TABLE")
ngx.say(result[]["ID"])
ngx.say(result[]["NAME"])

4、直接Redis

local redis = require "resty.redis"
local cache = redis.new()
cache.connect(cache,"10.10.3.208", "")
local result = cache:get("key")

5、使用管道

local redis = require "resty.redis"
local cache = redis.new()
cache.connect(cache,"10.10.3.208", "")
cache:init_pipeline()
for i=, do
cache:get("key")
end
local res = cache:commit_pipeline()
for j=,#res do
ngx.say(res[j])
end

6、计算一共有多少页

local totalPage = math.floor((totalRow+pageSize-)/pageSize)

7、Lua Table 多字段排序

--排列顺序优先级从高到低依次为:
--第一:等级由高到低;
--第二:稀有度由高到低;
--第三:伙伴ID从高到低。
local function sort_(a, b)
local r
local al = tonumber(a.level)
local bl = tonumber(b.level)
local aq = tonumber(a.data.quality)
local bq = tonumber(b.data.quality)
local aid = tonumber(a.pid)
local bid = tonumber(b.pid)
if al == bl then
if aq == bq then
r = aid > bid
else
r = aq > bq
end
else
r = al > bl
end
return r
end table.sort(tableName,sort_)

8、四舍五入小数点保留2位

local function keepTwoDecimalPlaces(decimal)
decimal = math.floor((decimal * )+0.5)*0.01
return decimal
end ngx.say(keepTwoDecimalPlaces(1.369))