萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Nginx 反向代理自動化配置:基於 RabbitMQ 事件驅動的動態路由

架構概覽

  • 微服務啟動時發布 AddApiClaim 消息到 RabbitMQ(含 claim、IP、Port)。
  • ProxyAutomation 服務消費消息,生成 Nginx 配置片段,SCP 部署並 nginx -s reload。
  • Nginx 通過 include 通配符動態加載上游與路由配置。

Nginx 主配置

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    include /etc/nginx/conf.d/*.conf;
}

# conf.d/api.example.com.conf
include /etc/nginx/conf.d/api.example.com.conf.d/upstream.*.conf;

server {
    listen 80;
    server_name api.example.com;
    include /etc/nginx/conf.d/api.example.com.conf.d/location.*.conf;
    location / { root /usr/share/nginx/api.example.com; }
}

動態生成的配置片段

upstream.stock.conf

upstream stock {
    server 10.0.0.23:8001;
    server 10.0.0.23:8002; # 輪詢負載均衡
}

location.stock.conf

location /stock/ {
    proxy_pass https://stock;
}

自動化組件關鍵點

  • 使用 SSH.NET 庫執行遠程 SCP 與命令。
  • 新增服務 → 寫入 upstream.xxx.conf + location.xxx.conf → reload。
  • 下線服務 → 刪除對應條目或文件 → reload。
  • 配置模板化,避免手動拼接錯誤。

優勢

  • 服務發現與路由配置解耦,開發者無需關心 Nginx。
  • 支持多實例輪詢,自動實現負載均衡。
  • 配置變更秒級生效,適應彈性伸縮場景。

總結

事件驅動的 Nginx 配置自動化,將反向代理從靜態配置提升為動態基礎設施組件,完美契合微服務與雲原生架構的服務發現需求。

copyright © 萬盛學電腦網 all rights reserved