Nginx+Lua实现分布式缓存
source link: https://wakzz.cn/2018/12/11/nginx/Nginx+Lua%E5%AE%9E%E7%8E%B0%E5%88%86%E5%B8%83%E5%BC%8F%E7%BC%93%E5%AD%98/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Nginx+Lua实现分布式缓存
local redis = require("resty.redis")
local cjson = require("cjson")
local cjson_encode = cjson.encode
local ngx_log = ngx.log
local ngx_ERR = ngx.ERR
local ngx_exit = ngx.exit
local ngx_print = ngx.print
local ngx_re_match = ngx.re.match
local ngx_var = ngx.var
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_log(ngx_ERR, "set redis keepalive error : ", err)
end
end
local function read_redis(id)
local red = redis:new()
red:set_timeout(1000)
local ip = "127.0.0.1"
local port = 1111
local ok, err = red:connect(ip, port)
if not ok then
ngx_log(ngx_ERR, "connect to redis error : ", err)
return close_redis(red)
end
local resp, err = red:get(id)
if net resp then
ngx_log(ngx_ERR, "get redis connect error : ", err)
return close_redis(red)
end
-- 得到的数据为空处理
if resp == ngx.null then
resp = nil
end
close_redis(red)
return resp
end
local function read_http(id)
local resp = ngx.location.capture("/backend", {
method = ngx.HTTP_GET,
args = {id = id}
})
if not resp then
ngx_log(ngx_ERR, "request error :", err)
return
end
if resp.status ~= 200 then
ngx_log(ngx_ERR, "request error, status :", resp.status)
return
end
return resp.body
end
-- 获取id
local id = ngx_var.id
-- 从redis获取
local content = read_redis(id)
-- 如果redis没有,则回源到tomcat
if not content then
ngx_log(ngx_ERR, "redis not found content, back to http, id : ", id)
content = read_http(id)
end
-- 如果还没有,则返回404
if not content then
ngx_log(ngx_ERR, "http not found content, id : ", id)
return ngx_exit(404)
end
-- 输出内容
ngx.print("show_ad(")
ngx.print(cjson_encode({content = content}))
ngx.print(")")
Recommend
-
11
Measuring Nginx Cache Performance using Lua and Redis February 23, 2016 22:15 / lua
-
1
Nginx+Lua环境搭建 祈雨的博客 2018-12-15
-
3
通过nginx+lua+redis可以实现nginx动态从redis读取需要拒绝的ip黑名单列表,并拒绝黑名单ip的访问请求。 其中redis中的ip黑名单列表既可以人工后台手动添加,也可以用类似logstash+elasticsearch的组合,实现logstash实时读取nginx的访问日志acces...
-
2
nginx_lua 扩展让 nginx 拥有可编程能力 发表于...
-
4
[译]Nginx和Lua 04 Sep 2012 By 风之缘 这几个月里,我们逐步把Lua集成到Mixlr的前端Nginx配置中。 Lua是一个可以嵌入到Nginx配置文件中的动态脚本语言,...
-
3
Nginx+Lua实现访问日志收集系统 | 是潘达呀Nginx+Lua实现访问日志收集系统 发表于 2017-12-28 | 分类于 开发 | | 浏览4 次 | 字数统计: 1.4k | 阅读时长 ≈ 6网站数据统...
-
8
lua-nginx-module的所有指令以及所有方法 2022-10-30 17:13:00 http://www....
-
3
https://blog.51cto.com/xikder/2331336 https://blog.51cto.com/xikder/2331368
-
1
Nginx与LUA(1) 精选 原创 湘王爱娟娟 2023-01-10 16:31:03...
-
1
Nginx与LUA(2) 精选 原创 湘王爱娟娟 2023-01-12 17:53:34...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK