首页 > 解决方案 > 是否可以对所有负载平衡上游服务器执行特定请求?

问题描述

我正在使用 NGINX 服务器将 HTTP 请求和负载平衡请求代理到多个上游服务器。但是我有一个特定的要求来执行对所有上游服务器的特定请求。

是否可以使用 NGINX 负载平衡?

我正在使用以下 nginx 配置

http {
    upstream myapp1 {
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://myapp1;
        }
    }
}

我有一个特定的请求(/update),如下所示,它需要在所有上游服务器中执行,并且(/update)以外的所有其他请求都应该按照负载平衡策略执行。

http {
    upstream myapp1 {
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

    server {
        listen 80;

        location /update {
            proxy_pass http://myapp1;
        }
    }
}

标签: nginx

解决方案


我认为在 nginx 中广播请求没有这样的规定。

在我看来,有两种选择可以实现这一目标

  1. 创建将在所有服务器上执行给定操作的单独服务。例如,在您的任何应用程序服务器上创建一个 php 文件 update.php 或将其托管在 nginx 服务器本身上并发出 curl 请求或向所有上游服务器发送请求。

更新.php

<?php
file_get_contents("srv1.example.com/update");
file_get_contents("srv2.example.com/update");
file_get_contents("srv3.example.com/update");
?>

如果您想发布可以使用 curl 的数据,上面的脚本只是向服务器发出请求。

http {
    upstream myapp1 {
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://myapp1;
        }


        location /update {
            proxy_pass "http://servername/update.php";
        }

    }
}

  1. 使用提供 ngx.location.capture_multi 和 ngx.location.capture 函数的 nginx lua 模块将请求发送到所有需要的 url。

https://github.com/openresty/lua-nginx-module#ngxlocationcapture_multi


推荐阅读