The behavior depends on whether you're using reqwest::blocking::Client
(sync) or reqwest::Client
(async).
Whether or not the existing connection is reused can be checked by enabling debug log.
reqwest::blocking::Client
When using synchronous API, just reusing a client means reusing a connection.
This is because, at the second (or third or ...) time we use the client, it is guaranteed the first call has completed and we have a connection.
use std::env;
use reqwest::blocking::Client;
fn main() {
env::set_var("RUST_LOG", "debug");
env_logger::init();
let client = Client::new();
for _ in 0..3 {
//calls an API which returns a random string
let res = client
.get("https://ciprand.p3p.repl.co/api?len=10&count=1")
.send()
.unwrap();
println!("{}", res.text().unwrap());
}
}
[2023-05-17T07:11:13Z DEBUG reqwest::connect] starting new connection: https://ciprand.p3p.repl.co/
{"Strings":["fa749eda765"],"Count":1,"Length":10}
{"Strings":["dd0a8bfdc57"],"Count":1,"Length":10}
{"Strings":["cdedd8e3982"],"Count":1,"Length":10}
(Only one starting new connection
is printed.)
reqwest::Client
When using asynchronous API, just reusing a client does NOT mean reusing a connection.
This is because, at the second (or third or ...) time we use the client, it is NOT guaranteed the first call has completed and we have a connection.
(The code below is for experiment purpose: never write an async code like this.)
use std::{env, sync::Arc};
use reqwest::Client;
async fn call(url: &str, client: Arc<Client>) {
client.get(url).send().await.unwrap();
println!("completed");
}
#[tokio::main]
async fn main() {
env::set_var("RUST_LOG", "debug");
env_logger::init();
let client = Arc::new(Client::new());
for _ in 0..2 {
tokio::spawn(call(
"https://ciprand.p3p.repl.co/api?len=10&count=1",
client.clone(),
));
}
std::thread::sleep(std::time::Duration::from_millis(1000));
for _ in 0..2 {
tokio::spawn(call(
"https://ciprand.p3p.repl.co/api?len=10&count=1",
client.clone(),
));
}
std::thread::sleep(std::time::Duration::from_millis(1000));
}
[2023-05-17T07:14:25Z DEBUG reqwest::connect] starting new connection: https://ciprand.p3p.repl.co/
[2023-05-17T07:14:25Z DEBUG reqwest::connect] starting new connection: https://ciprand.p3p.repl.co/
completed
completed
completed
completed
(Only two starting new connection
are printed. This is because, at the third and fourth time we use the client, the first (or maybe the second) call has completed by chance and we have a connection.)