系统环境:CentOS7.6
1 添加源
yum install yum-utils
yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
2 执行安装
yum install openresty
3 openresty内置了nginx,修改其conf文件
cd /usr/local/openresty/nginx/conf
ls
vi nginx.conf
4 给nginx.conf文件server 添加如下一段
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
#应该只要添加下面的
#用户请求url/update_content?id=1 拦截,交由lua脚本控制
location /update_content {
content_by_lua_file /mine/lua/update_content.lua;
}
}
5 lua安装
6 访问远程服务器ip 80端口
7 openresty+lua 的首页广告缓存高可用测试,步骤如下:
核心意思:url请求被拦截–>交由lua脚本控制–>先查询nginx cache ^1 ,若没有–>查询redis,若没有 ^2 -->查询数据库 ^3
- 如果到^2步返回数据,会将数据缓存到nginx cache
- 如果到^3步返回数据,会将数据缓存到redis
8 在根目录下创建文件夹mine/lua,创建测试文件update_content.lua内容如下:
ngx.header.content_type="application/json;charset=utf8"
local cjson = require("cjson")
local mysql = require("resty.mysql")
local uri_args = ngx.req.get_uri_args()
local id = uri_args["id"]
local db = mysql:new()
db:set_timeout(1000)
local props = {
host = IP
port = 3306,
database = "changgou_content",
user = "root",
password = PWD
}
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)
db:close()
local redis = require("resty.redis")
local red = redis:new()
red:set_timeout(2000)
local ip = IP
local port = 6379
red:connect(ip, port)
red:set("content_"..id,cjson.encode(res))
red:close()
ngx.say("{flag:true}")
9 重载配置文件
cd /usr/local/openresty/nginx/conf
10 测试请求
注:
- 如果有说什么nginx.log文件不存在,是配置文件没有关联。
/usr/local/openresty/nginx/sbin/nginx -c /usr/local/openresty/nginx/conf/nginx.conf
- 以上是测试,具体实现:
在 /mine/lua文件夹下创建read_content.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;
--根据ID 获取本地缓存数据
local contentCache = cache_ngx:get('content_cache_'..id);
if contentCache == "" or contentCache == nil then
--引入redis库
local redis = require("resty.redis");
--创建redis对象
local red = redis:new()
--设置超时时间
red:set_timeout(2000)
--连接
red:connect(IP, 6379)
local rescontent=red:get("content_"..id);
if ngx.null == rescontent then
local cjson = require("cjson");
local mysql = require("resty.mysql");
local db = mysql:new();
db:set_timeout(2000)
local props = {
host = IP
port = 3306,
database = "changgou_content",
user = "root",
password = PWD
}
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);
local responsejson = cjson.encode(res);
red:set("content_"..id,responsejson);
ngx.say(responsejson);
db:close()
else
cache_ngx:set('content_cache_'..id, rescontent, 10*60);
ngx.say(rescontent)
end
red:close()
else
ngx.say(contentCache)
end
修改nginx.conf,添加内容如下:
cd /usr/local/openresty/nginx/conf
vi nginx.conf
重载配置文件,见9。请求访问:
查询的是数据库,并且将缓存存入了redis