网站首页 > 基础教程 正文
有时我们想根据用户请求的参数转发到不同的upstream,像做多机房用户路由的时候是非常有用的,实现有多种方式,一是设置不同的loction,然后让lua动态执行不同的子请求;还有就是将upstream设置成变量,让lua动态计算出返回哪个upstream;
下面演示第二种方式,假设我们的域名为aa.com,nginx配置如下:
upstream order0{
server 127.0.0.1:12580;
}
upstream order1{
server 127.0.0.1:11580;
}
server {
listen 443 ssl;
server_name aa.com;
location / {
set_by_lua_file $ups /data/lua/upsteam.lua;
add_header X-CLOSED 0;
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Accept-Encoding "";
proxy_set_header X-Scheme $scheme;
client_max_body_size 200m;
proxy_pass http://$ups;
}
}
上面的配置设置了2个upsteam,通过set_by_lua_file指令设置变量ups,然后请求到ups变量指向的upstream中,lua代码如下:
--ip to hash函数
function iptolong(ip)
local first_index = 1
local last_index = 1
local cur_index=1
local arr = {}
local res
local split_str
split_str = "%."
while true do
first_index,_ = string.find(ip, split_str, last_index)
if nil == first_index then
arr[cur_index] = string.sub(ip, last_index, string.len(ip))
break
end
arr[cur_index] = string.sub(ip, last_index, first_index - 1)
last_index = first_index + 1
cur_index = cur_index + 1
end
res = tonumber(arr[1])*256*256*256;
res = res + tonumber(arr[2])*65536;
res =res + tonumber(arr[3])*256;
res = res + tonumber(arr[4]);
return res
end
local ip = ngx.var.remote_addr;
local ip_hash
ip_hash = iptolong(ip) % 2;
if ip_hash == 1 then
return "order1"
else
return "order0"
end
上面我们根据用户的IP做Hash计算,结果为0的返回order0,反之返回order1,即不同的IP返回不同的Upstream;然后可以在浏览器访问 aa.com的一个地址,可以让每个服务器返回不同的东西就可以看到效果了。
猜你喜欢
- 2024-10-23 按键精灵自动寻路系列换算地图坐标寻路法
- 2024-10-23 [Redis],Lua分步式限流方案,限流分几步?
- 2024-10-23 基于FEKO软件的目标RCS计算及数据分析
- 2024-10-23 [按键精灵]会员时间相关计算/转换的代码讲解
- 2024-10-23 lua math.deg使用 lua的match
- 2024-10-23 梯度下降方法与求导 梯度下降求导过程
- 2024-10-23 redisson实现分布式锁原理 redisson分布式锁问题
- 2024-10-23 万字长文:从源码学习GopherLua与工程实践
- 2024-10-23 LUA入门简易小应用 lua用什么软件编程
- 2024-10-23 lua math.asin使用 lua assert函数
- 05-14CSS基础知识(一) CSS入门
- 05-14CSS是什么? CSS和HTML有什么关系?
- 05-14什么是CSS3?
- 05-14CSS如何画一个三角形?
- 05-14初识CSS——CSS三角制作
- 05-14Wordpress建站教程:给图片添加CSS样式
- 05-14HTML和HTML5,css和css3的区别有哪些?
- 05-14Html中Css样式Ⅱ
- 最近发表
- 标签列表
-
- jsp (69)
- pythonlist (60)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- mysql教程 (60)
- pythonif (86)
- location.href (69)
- deletesql (62)
- c++模板 (62)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- console.table (62)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)