首先创建一个lua文件
ngx.log(ngx.ERR,"lua sucess");
在nginx配置文件中加:
启动nginx:
也就是说这个脚本会在nginx启动的时候执行。当然,一般用的不多,用的更多的是content_by_lua来指定lua实现什么样的内容,接下来试一下:
配置下nginx
新建lua脚本:
ngx.say("hello static item lua");
重启后访问配置的地址:
文件打开后是:
因为没有指定http的default type,所以默认是文件的形式,接下来指定一下:
重启后:
对于OpenResty,我们之前已经介绍过了,他是由Nginx核心加很多第三方模块组成的,默认集成了Lua开发环境,使得nginx可以作为一个web server使用,借助于nginx的事件驱动模型和非阻塞io,可以实现高性能的web应用程序。并且提供了大量的组件如Mysql、Redis、Memcached等,使nginx上开发web应用更方便更简单。
实战开始:
同样新建lua脚本:
ngx.exec("/item/get?id=6");
nginx配置:
重启nginx
所以ngx.exec相当于转发。
接下来认识一下nginx shared dic,这是共享内存字典,所有worker进程可见,可以指定lru淘汰规则。
配置一下shared dic:
写lua脚本:
function get_from_cache(key)
local cache_ngx = ngx.shared.my_cache
local value = cache_ngx:get(key)
return value
end
function set_to_cache(key,value,exptime)
if not exptime then
exptime = 0
end
local cache_ngx = ngx.shared.my_cache
local succ,err,forcible = cache_ngx:set(key,value,exptime)
return succ
end
local args = ngx.req.get_uri_args()
local id = args["id"]
local item_model = get_from_cache("item_"..id)
if item_model == nil then
local resp = ngx.location.capture("/item/get?id="..id)
item_model = resp.body
set_to_cache("item_"..id,item_model,1*60)
end
ngx.say(item_model)
配置nginx
结果:
这样就减轻了应用服务器的压力,但是相对的压力也全都在nginx服务器上了。当然它的更新机制跟之前说的内存缓存一样,并不是很好,因此时间还是变成了一个很重要的一环,或者用redis:
nginx对于redis只读不写,当读不出来的时候就发给应用程序,由应用程序来写,这样对于脏读的面就小了很多。甚至可以在扩展redis主从机后,只从slave上读。
写脚本:
local args = ngx.req.get_uri_args()
local id = args["id"]
local redis = require "resty.redis"
local cache = redis:new()
local ok,err = cache:connect("172.18.57.95",6379)
local item_model = cache:get("item_"..id)
if item_model == ngx.null or item_model == nil then
local resp = ngx.location.capture("/item/get?id="..id)
item_model = resp.body
end
ngx.say(item_model)
改配置:
运行结果都是一样的,这里不贴了。
当然在压测过程中,redis的压力会比较大,所以在生产环境中,我们可以用redis的cluster来分散压力。