双层OpenResty根据 productId 做 分流,


简单描述一下根据productId分流的步骤:

1、获取请求参数,比如productId

2、对productId进行hash

3、hash值对应用服务器数量取模,获取到一个应用服务器

4、利用http发送请求到应用层nginx

5、获取响应后返回


这个就是基于商品id的定向流量分发的策略,lua脚本来编写和实现

我们作为一个流量分发的nginx,会发送http请求到后端的应用nginx上面去,所以要先引入lua http lib包

cd /usr/hello/lualib/resty/

wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http_headers.lua

wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http.lua


修改 /usr/hello/lua/hello.lua 文件的内容:

代码:

local uri_args = ngx.req.get_uri_args()

local productId = uri_args["productId"]

local host = {"192.168.18.128:8091", "192.168.18.128:8092"}

local hash = ngx.crc32_long(productId)

hash = (hash % 2) + 1

backend = "http://"..host[hash]

local method = uri_args["method"]

local requestBody = "/"..method.."?productId="..productId

local http = require("resty.http")

local httpc = http.new()

local resp, err = httpc:request_uri(backend, {

method = "GET",

path = requestBody

})

if not resp then

ngx.say("request error :", err)

return

end

ngx.say(resp.body)

httpc:close()


由于机器内存太小,只能在一台机器上搞了

在 usr/hello 下面 建立 part1.conf      part2.conf 配置文件



在 /usr/hello/lua 下面 建立 part1.lua  part2.lua





在 /usr/servers/nginx/conf 下面的 nginx/conf 加上 下面2句


重启 nginx:

/usr/servers/nginx/sbin/nginx -s reload


通过 :

http://192.168.18.128:8090/lua?productId=1&method=part  

访问 修改 productId 的值 ,就会访问 不同的 业务层







简单描述一下: 第一次 OpenResry 做根据 productId 做分流 ,第二层 用 lua 写业务逻辑

第一次 根据 produId 分流到 第二层 OpenResry上面, 可以做到 缓存命中率大大提高

相关内容

    暂无相关文章