Reqwest Pool Timeout Configuration

Tune reqwest connection pooling with per-host keepalives, idle timeouts, and layered timeouts for connect, read, and total budgets.

RustData Fetching

Code

snippet
use std::time::Duration;

use reqwest::Client;

fn build_client() -> reqwest::Result<Client> {
    Client::builder()
        .pool_max_idle_per_host(16)
        .pool_idle_timeout(Duration::from_secs(90))

        .connect_timeout(Duration::from_secs(3))
        .timeout(Duration::from_secs(10))
        .redirect(reqwest::redirect::Policy::limited(3))
        .user_agent("billing-sync/2.1")
        .build()
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::builder()
        .pool_max_idle_per_host(16)
        .pool_idle_timeout(Duration::from_secs(90))
        .connect_timeout(Duration::from_secs(3))
        .timeout(Duration::from_secs(10))
        .build()?;

    let started = std::time::Instant::now();

    // 第一次请求建立连接,后续复用同一池内连接
    let first = client
        .get("https://api.example.com/invoices")
        .query(&[("page", "1")])
        .send()
        .await?
        .json::<serde_json::Value>()
        .await?;
    println!("first took {:?}", started.elapsed());

    let second = client
        .get("https://api.example.com/invoices")
        .query(&[("page", "2")])
        .send()
        .await?
        .json::<serde_json::Value>()
        .await?;
    println!("second took {:?}", started.elapsed());

    println!(
        "pages fetched: {} {}",
        first.get("page").and_then(|v| v.as_i64()).unwrap_or(0),
        second.get("page").and_then(|v| v.as_i64()).unwrap_or(0)
    );

    let _ = build_client()?;
    Ok(())
}