反向代理

反向代理是一種伺服器架構,它接收來自客戶端的請求並將其轉發到後端的一個或多個伺服器。與正向代理(代表客戶端)不同,反向代理代表伺服器端工作。

反向代理的主要優勢:

  • 負載均衡:分散請求到多個伺服器
  • 安全性提升:隱藏真實伺服器資訊
  • 內容快取:提高效能
  • 路徑重寫與轉發:靈活地路由請求

Salvo 框架提供反向代理功能的中介軟體。

範例程式碼

main.rs
Cargo.toml
use salvo::prelude::*;

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt().init();

    // In this example, if the requested URL begins with <http://127.0.0.1:8698/>, the proxy goes to
    // <https://www.rust-lang.org>; if the requested URL begins with <http://localhost:8698/>, the proxy
    // goes to <https://crates.io>.
    let router = Router::new()
        .push(
            Router::new()
                .host("127.0.0.1")
                .path("{**rest}")
                .goal(Proxy::use_hyper_client("https://docs.rs")),
        )
        .push(
            Router::new()
                .host("localhost")
                .path("{**rest}")
                .goal(Proxy::use_hyper_client("https://crates.io")),
        );

    let acceptor = TcpListener::new("0.0.0.0:8698").bind().await;
    Server::new(acceptor).serve(router).await;
}