Mat*_*nti 5 rest https rust reqwest
我需要向同一台服务器发出一长串 REST 调用(我们称之为myapi.com
)。目前,我使用 Rust 库reqwest
如下:
reqwest::Client
使用所有默认设置创建了一个。client.post("https://myapi.com/path/to/the/api")
创建一个reqwest::RequestBuilder
.RequestBuilder
以获得reqwest::Request
.send()
了。Request
reqwest::Response
Client
,重新开始。我在文档中读到reqwest
应该在同一个Client
. 鉴于我总是重复使用相同的Client
,我希望第一个 API 调用需要更多时间(由于初始 TCP 和 HTTPS 握手)。然而,我观察到所有请求始终存在一致的、相当高的延迟。所以,我想知道连接是否被重用,或者每次都重新建立。如果不是,我如何回收相同的连接?我觉得如果我能节省一些往返时间,延迟就会大大减少。
该行为取决于您使用的是reqwest::blocking::Client
(同步)还是reqwest::Client
(异步)。
可以通过启用调试日志来检查现有连接是否被重用。
reqwest::blocking::Client
当使用同步API时,仅仅重用客户端就意味着重用连接。
这是因为,在我们第二次(或第三次或……)使用客户端时,可以保证第一次调用已完成并且我们有一个连接。
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());
}
}
Run Code Online (Sandbox Code Playgroud)
[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}
Run Code Online (Sandbox Code Playgroud)
(仅starting new connection
打印一份。)
reqwest::Client
使用异步 API 时,仅重用客户端并不意味着重用连接。
这是因为,在我们第二次(或第三次或……)使用客户端时,不能保证第一次调用已完成并且我们有连接。
(下面的代码用于实验目的:永远不要编写这样的异步代码。)
[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}
Run Code Online (Sandbox Code Playgroud)
[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
Run Code Online (Sandbox Code Playgroud)
(只打印了两个starting new connection
。这是因为,在我们第三次和第四次使用客户端时,第一次(或者可能是第二次)调用偶然完成,并且我们建立了连接。)
归档时间: |
|
查看次数: |
2215 次 |
最近记录: |