openResty 服务器使用lua脚本实现更具请求参数,转发到不同的服务

介绍小需求

根据不同的请求参数转发到不同的服务

应用场景

  1. 可以更具用户Id进行Hash到不同的服务器上;
  2. 可以做nginx缓存,例如:商品详情页面,更具商品Id哈希取模请求转发到不同的nginx上;
  3. 更具请求中添加的参数区分环境,进行恢复发布(比如:正式环境、开发环境、预生产环境、演示环境、测试环境...);

具体需求,同一个请求不同参数转发到不同的服务上

http://192.168.0.111/a?a=2

http://192.168.0.111/a?a=1

1、配置nginx

server {
      listen       80;
      server_name  localhost; 
      access_log  /opt/lua/host.access.log;
      charset utf-8;
      location /a {
         default_type text/html;
         lua_code_cache on;
         rewrite_by_lua_file /opt/lua/1.lua;
      }
      location @b {
         # 这里可以做请求转发到相应的服务上 
         default_type text/html;
         lua_code_cache on; 
         content_by_lua_block {
                ngx.say("<p>b</p>")
         }
      }
      location @c {
          # 这里可以做请求转发到相应的服务上
          default_type text/html;
          lua_code_cache on; 
          content_by_lua_block {
                ngx.say("<p>c</p>")
            }
      }
 }

1.lua脚本文件

 

local request_method = ngx.var.request_method
local args = nil
local param= nil
if "GET" == request_method then
    args = ngx.req.get_uri_args()
elseif "POST" == request_method then
    ngx.req.read_body()
    args = ngx.req.get_post_args()
end
param = args["a"]
if "1" == param then
    ngx.exec("@b")
elseif "2" == param then
    ngx.exec("@c")
end

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值