原创

使用Lua完成Cache+DataBase查询

1.Lua脚本代码
--设置响应头类型
ngx.header.content_type="application/json;charset=utf8"
----获取请求中的参数ID
local uri_args = ngx.req.get_uri_args();
local id = uri_args["id"];

--获取本地缓存中的数据
local cache_ngx = ngx.shared.dis_cache;
local contentCache = cache_ngx:get('conetent_cache_'..id);

-- 判断是否有缓存
if contentCache == "" or contentCache == nil then
	--引入redis库
	local redis = require("resty.redis");
	--创建redis对象
	local red = redis:new()
	--设置超时时间
	red:set_timeout(2000)
	--连接
	local ok, err = red:connect("122.112.252.143", 6379)
	--获取key的值
	local rescontent=red:get("content_"..id)
		-- redis为空
	if rescontent == ngx.null then
		local cjson = require("cjson")
		local mysql = require("resty.mysql")
		local db = mysql:new();
		db:set_timeout(2000)
		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";
		res = db:query(select_sql);
		red:set("content_"..id,cjson.encode(res));
		ngx.say(cjson.encode(res));
		db:close()
	else
		--输出到返回响应中
		ngx.say(rescontent)
		--将redis中读取的数据 存入nginx本地缓存
		cache_ngx:set('conetent_cache_'..id,rescontent,10*60);
	end
	--关闭连接
	red:close()
else
ngx.say(contentCache)
end

2.需要在Nginx.conf中配置缓存模块及可用内存大小
lua_shared_dict dis_cache 5m;
Lua

留言板