From 74f35faa224a06d684f6fbaf97553c3e1dd70eab Mon Sep 17 00:00:00 2001 From: asonix Date: Fri, 23 Jun 2023 15:01:56 -0500 Subject: [PATCH] Keep client in thread-local storage --- src/requests.rs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/requests.rs b/src/requests.rs index b71e6d1..a1fc8ef 100644 --- a/src/requests.rs +++ b/src/requests.rs @@ -162,15 +162,25 @@ impl std::fmt::Debug for Requests { } } -pub(crate) fn build_client(user_agent: &str, pool_size: usize) -> Client { - let connector = Connector::new().limit(pool_size); +thread_local! { + static CLIENT: std::cell::OnceCell = std::cell::OnceCell::new(); +} - Client::builder() - .connector(connector) - .wrap(Tracing) - .add_default_header(("User-Agent", user_agent.to_string())) - .timeout(Duration::from_secs(15)) - .finish() +pub(crate) fn build_client(user_agent: &str, pool_size: usize) -> Client { + CLIENT.with(|client| { + client + .get_or_init(|| { + let connector = Connector::new().limit(pool_size); + + Client::builder() + .connector(connector) + .wrap(Tracing) + .add_default_header(("User-Agent", user_agent.to_string())) + .timeout(Duration::from_secs(15)) + .finish() + }) + .clone() + }) } impl Requests {