lua模块demo(redis,http,mysql,cjson,本地缓存)

lua模块demo(redis,http,mysql,cjson,本地缓存),第1张

概述1. lua模块demo(redis,http,mysql,cjson,本地缓存) 1.1. 配置 在nginx.conf中设置lua_shared_dict my_cache 128m; 开启nginx本地缓存,放到http{} 层 location配置 location /redis-get{ resolver 8.8.8.8; default_type text/html; 1. lua模块demo(redis,http,MysqL,cJson,本地缓存) 1.1. 配置 在Nginx.conf中设置lua_shared_dict my_cache 128m; 开启Nginx本地缓存,放到http{} 层 location配置
location /redis-get{    resolver 8.8.8.8;    default_type text/HTML;    content_by_lua_file /usr/local/openresty/lua/redis-get.lua;}
这里推荐个工具,使用notepad++,下载个插件NppFtp,效果如下图,可以直接对liunx上的文件进行编辑保存

1.2. http 远程调用可以使用该模块 https://github.com/ledgetech/lua-resty-http 把lib包里的两个文件复制到 /usr/local/openresty/lualib/resty 通过require("resty.http") 调用 1.3. MysqL 连接工具
local connectMysqLUtil = {}local MysqL = require "resty.MysqL"-- connect to MysqL;function connectMysqLUtil.connect()    local db,err = MysqL:new()    if not db then        return false    end    db:set_timeout(1000)        local ok,err,errno,sqlstate = db:connect{        host = "127.0.0.1",port = 8083,database = "test",user = "dev",password = "1234",max_packet_size = 1024 * 1024 }        if not ok then        ngx.say("connect MysqL Failed")        return false    end    return dbendreturn connectMysqLUtil

参考 https://www.cnblogs.com/zhuzi91/p/7879956.html

1.4. string工具
local stringEx = {}function stringEx.ToStringEx(value)    if type(value)=='table' then       return stringEx.tableToStr(value)    elseif type(value)=='string' then        return "\'"..value.."\'"    else       return tostring(value)    endendfunction stringEx.tableToStr(t)    if t == nil then return "" end    local retstr= "{"    local i = 1    for key,value in pairs(t) do        local signal = ","        if i==1 then          signal = ""        end        if key == i then            retstr = retstr..signal..stringEx.ToStringEx(value)        else            if type(key)=='number' or type(key) == 'string' then                retstr = retstr..signal..'['..stringEx.ToStringEx(key).."]="..stringEx.ToStringEx(value)            else                if type(key)=='userdata' then                    retstr = retstr..signal.."*s"..stringEx.tableToStr(getMetatable(key)).."*e".."="..stringEx.ToStringEx(value)                else                    retstr = retstr..signal..key.."="..stringEx.ToStringEx(value)                end            end        end        i = i+1    end     retstr = retstr.."}"     return retstrendfunction stringEx.StrTotable(str)    if str == nil or type(str) ~= "string" then        return    end        return loadstring("return " .. str)()endreturn stringEx
1.5. 整合redis+本地缓存
-- 自定义的字符串转换工具local stringEx = require("stringExt")-- 本地缓存local local_cache = ngx.shared.my_cache-- redis连接池,设置连接空闲时间local function close_redis(red)    if not red then        return    end    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 fail ",err)    endend-- 读Redis缓存local function read_redis(key)    local redis = require("resty.redis")    local red = redis.new();    local ok,err = red:connect("127.0.0.1",8084)    if not ok then         ngx.say("connect fail ",err)        return close_redis(red)    end    red:set_timeout(1000)    local count,err = red:get_reused_times()    if 0==count then        ok,err = red:auth("123456")        if not ok then            ngx.say("auth fail ",err)            return close_redis(red)        end    elseif err then        ngx.say("fail to get reused times")        return close_redis(red)    end    local res,err = red:get(key)    if not res then        ngx.say("get msg fail ",err)        return close_redis(red)    elseif res then        ngx.say(" set expire 10000 ")        red:expire(key,10)    end    local_cache:set(key,res,5)    ngx.say("read from redis ")    ngx.say(res)    close_redis(red)end-- http请求参数local args = ngx.req.get_uri_args()local key = args["key"]if not key then     ngx.say("key must be exist")    returnendlocal keyCache = local_cache:get(key)if not keyCache then    local res = read_redis(key)    if not res then        ngx.say("redis is null")    endelse    ngx.say("read from localCache ")    ngx.say(keyCache)end-- http调用工具,需要额外下载,地址:https://github.com/ledgetech/lua-resty-http 说明:https://blog.csdn.net/xIEjunna/article/details/53445342local http = require("resty.http")local httpc = http.new();if not httpc then     ngx.say("\n\r httpc new fail")endhttpc:set_timeout(8000)-- keepalive参数不写可能导致报错local res,err = httpc:request_uri("http://www.xxx.com",{    method="POST",path="/xxx/rpc.API",body = 'a=1&b=2',headers = {          ["Content-Type"] = "application/x-www-form-urlencoded",},keepalive_timeout = 60,keepalive_pool = 10})if not res then    ngx.say("httpc call fail ")    returnendlocal cJson = require("cJson")local Json = cJson.new()if not Json then    ngx.say("Json is null")    returnend-- 测试调用结果-- ngx.say(stringEx.tableToStr(res))-- ngx.say(stringEx.ToStringEx(Json.decode(res["body"])))-- ngx.say(type(Json.decode(res["body"])))-- ngx.say(stringEx.ToStringEx(Json.decode(res["body"])["header"]["request_seq"]))-- ngx.say(type(Json.decode(res["body"])["header"]))-- ngx.say(type(Json.decode(res["body"])["header"]["request_seq"]))local connectMysqLUtil = require("connectMysqLUtil")local db = connectMysqLUtil.connect()if not db then    ngx.exit(ngx.http_INTERNAL_SERVER_ERROR)    returnendlocal res,errcode,sqlstate = db:query("select * from t_uls_order_info where order_ID='20190119232946000023'",10)if not res then    ngx.say("bad request: ",":",": ",sqlstate,".")    returnendngx.say("result:",Json.encode(res))
1.6. 总结 本文记录了对http,MysqL,redis,Nginx本地缓存的基本使用方式,后续需要使用到该模块的需求可以直接参考修改本示例代码 对于实际的互联网需求,这里可以想象个基于这些模块的需求,优先读取ngnix本地缓存,过期时间较短,其次读取Redis缓存,减少redis压力,进一步减少MysqL读取压力 总结

以上是内存溢出为你收集整理的lua模块demo(redis,http,mysql,cjson,本地缓存)全部内容,希望文章能够帮你解决lua模块demo(redis,http,mysql,cjson,本地缓存)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1231603.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存