简体   繁体   English

负载均衡器中的自定义路由

[英]Custom routing in load balancer

Is it possible to define a custom routing in NGINX or other Load Balancer? 是否可以在NGINX或其他负载均衡器中定义自定义路由? Ie I have a cookie or a header and based on its value I decide which backend server to choose? 即我有一个cookie或标题,并根据其价值我决定选择哪个后端服务器? I need some very simple logic - values a1,a2,a3 - to server A, values b1,b2 to server B, all other to server C 我需要一些非常简单的逻辑 - 值a1,a2,a3 - 到服务器A,值b1,b2到服务器B,所有其他逻辑到服务器C

In nginx you can do it simply by using if: 在nginx中,您只需使用if即可:

location / {
    if ($http_cookie  ~* "yourcookiename=a") {
        proxy_pass http://upstream_a;
        break;
    }
    if ($http_cookie ~* "yourcookiename=b") {
        proxy_pass http://upstream_b;
        break;
    }
    proxy_pass http://upstream_c;
}

This is simple regexp , so this way if "yourcookiename" has value a1,a2 etc. it will go to uprstream_a and so on. 这是简单的正则表达式,所以这种方式如果“yourcookiename”具有值a1,a2等,它将转到uprstream_a,依此类推。 Hope it helps... 希望能帮助到你...

If you need some sticky session, there are open source third party modules that can do that with nginx, while the native implementation is part of the commercial subscription. 如果你需要一些粘性会话,有开源的第三方模块可以用nginx做到这一点,而本机实现是商业订阅的一部分。 Also, tengine, an open source chinese fork of nginx developed by Alibaba can do that natively. 此外,由阿里巴巴开发的开源中文nginx分支机构tengine可以做到这一点。

If you want to do it the custom way, use a map to avoid processing a chain of if blocks for all requests. 如果您想以自定义方式执行此操作,请使用映射以避免为所有请求处理if块链 This is also better for readability. 这对于可读性来说也更好。 For instance, using a cookie : 例如,使用cookie:

map $cookie_mycookie $node {
    "~^a[1-3]$" "A";
    "~^b[1-2]$" "B";
    default     "C";
}

server {

    location / {
        proxy_pass http://$node;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM