实现多级缓存,首先得知道什么是多级缓存
多级缓存就是缓存分布在不同的地方
首先缓存在nginx 中,然后 Redis ,然后 mysql
首先新建一个文件nginx_lua.lua脚本
--设置头信息
ngx.header.content_type = "application/json;charset=utf8"
--获取缓存对象
local cache_ngx = ngx.shared.dis_cache;
local contentCache = cache_ngx:get("blog_index");
if contentCache == "" or contentCache == nil then
--引入Redis
local redis = require("resty.redis");
--获取Redis对象
local red = redis:new()
red:set_timeout(2000)
red:connect("172.17.0.4", 6379)
local rescontent = red:get("blog_index");
if ngx.null == rescontent or false == rescontent or "" == rescontent then
local cjson = require("cjson");
--获取MySQL对象
local mysql = require("resty.mysql");
local db = mysql:new();
db:set_timeout(2000)
local props = {
host = "172.17.0.3",
port = 3306,
database = "blog",
user = "root",
password = "root"
}
local res = db:connect(props);
local select_sql = "select * from blog_user"
res = db:query(select_sql);
local responsejson = cjson.encode(res);
red:set("blog_index", responsejson);
ngx.say(responsejson);
db:close()
else
cache_ngx:set("blog_index", rescontent, 10 * 60);
ngx.say(rescontent)
end
red:close()
else
ngx.say(contentCache)
end
nginx 配置文件
#这个是必须加的。表示设置了一块共享的内存区域,大小为10m.
lua_shared_dict dis_cache 10m;
server {
listen 90;
server_name localhost;
root /docker/openresty/www;
index index.html index.htm;
location /lmrs_home_index {
content_by_lua_file /docker/openresty/www/nginx_lua.lua;
}
}