参考资料
相应的api在这里可以找到
https://github.com/openresty/lua-nginx-module#nginx-api-for-lua
相应的lua模块
加载一些模块
https://www.nginx.com/resources/wiki/modules/lua/
https://github.com/pintsized/lua-resty-http/releases
题目:自行编写一个lua脚本实现流量的分发,按照自己的规则来分发 商品的id
需求: 做商品详情页的缓存
问题: 为了解决相同的内容重复的缓存,并且为了降低redis的压力
需求:基于商品的id进行流量分发
1、获取请求参数商品id
2、获取id的哈希值,取模做负载均衡,获取到一个地址
3、利用http请求,请求应用层服务器
4、响应回给客户端
准备3台机器cache01、cache02、cache03,用 cache01 和 cache02 作为应用层 Nginx服务器,用 cache03 作为分发层 Nginx。在cache03,也就是分发层 Nginx 中,编写 Lua脚本,完成基于 商品id 的流量分发策略
1> 获取请求参数,比如 productId
2> 对 productId 进行 hash
3> hash值 对应用服务器数量取模,获取到一个应用服务器
4> 利用 http 发送请求到应用层 nginx
5> 获取响应后返回
基于商品id的定向流量分发的策略,Lua脚本来编写和实现
作为一个流量分发的 Nginx,会发送 http请求到后端的应用 Nginx 上面去,所以要先引入 lua http lib包(一个网络请求的库)
1、首先引入lua http lib包
cd /tmp
wget https://github.com/ledgetech/lua-resty-http/archive/v0.14.tar.gz
tar -zxvf v0.14.tar.gz
cd lua-resty-http-0.14/lib/resty
cp http_headers.lua /usr/local/openresty/lualib/resty/
cp http.lua /usr/local/openresty/lualib/resty/
2、nginx配置
server{
....
#基于商品的id进行流量分发
location /distribute {
access_by_lua_file /usr/local/openresty/lualib/project/upstream/upstream.lua;
}
....
}
3、lua脚本如下:(存放位置自己定义,我这边是放在/usr/local/openresty/lualib/project/upstream)
--获取请求参数商品id
local uri_args = ngx.req.get_uri_args()
local productId = uri_args["productId"]
if productId == nil then
ngx.log(ngx.ERR,"参数不正确",productId)
return
end
--设定分发地址
local hosts = {"192.168.31.187", "192.168.31.19"}
--获取id的哈希值,取模做负载均衡,获取到一个地址
local hash,err = ngx.crc32_long(productId)
if hash == nil then
ngx.log(ngx.ERR,"hash失败")
return
end
--取模 获取hosts里的个数 table.getn(hosts)
local index = (hash % table.getn(hosts)) + 1
backend = "http://"..hosts[index]
--引入http包
local http = require("resty.http")
local httpc = http.new()
local resp, err = httpc:request_uri(backend,{
method = "GET",
keepalive_timeout = 60,
keepalive_pool = 10
})
if not resp then
ngx.say("request error: ", err)
return
end
ngx.status = res.status
ngx.say(resp.body)
httpc:close()
4、浏览器访问