原创

Nginx结合Lua脚本 实现高性能缓存机制

ngx.header.content_type="application/json;charset=utf8"
local cjson = require("cjson")
local mysql = require("resty.mysql")
-- 获取request中所传递的参数集合
local uri_args = ngx.req.get_uri_args()
-- 从参数中获取key为 id的参数
local id = uri_args["id"]

-- 数据库连接信息
local db = mysql:new()
db:set_timeout(1000)  
local props = {  
    host = "114.55.103.12",  
    port = 3306,  
    database = "changgou_content",  
    user = "root",  
    password = "root"  
}

-- 获取连接
local res = db:connect(props)  
local select_sql = "select url,pic FROM tb_content WHERE status = '1' AND category_id ="..id.." ORDER BY sort_order"  
-- 执行sql
res = db:query(select_sql)  
db:close()  

-- redis信息
local redis = require("resty.redis")
local red = redis:new()
red:set_timeout(2000)

local ip ="122.112.252.143"
local port = 6379
red:connect(ip,port)

red:set("content_"..id,cjson.encode(res))
red:close()

ngx.say("{flag:true}")

工作

留言板