尝试从 actix-web 路由处理程序函数中发出请求时出错"BlockingClientInFutureContext"



我正在使用 Rust 2018 Stable 和 Actix-Web 编写一个 Web 服务。使用 Reqwest,我从一个路由处理程序函数中向不同的站点发出 HTTP 请求。简单地说,它看起来像这样

extern crate reqwest;
use actix_web;
use reqwest::Url;
pub fn testing(req: actix_web::HttpRequest) -> actix_web::Result<actix_web::HttpResponse> {
println!(">>> testing request begin");
let url = Url::parse("https://example.com/").unwrap();
println!(">>> testing url built");
let req = reqwest::Client::new().post(url);
println!(">>> testing req prepared");
let res_struct = req.send();
println!(">>> testing res_struct received");
let res = res_struct.unwrap();
println!(">>> testing res unwrapped");
Ok(format!("done.").into())
}

这不起作用,我收到以下错误消息(错误打印了 8 次,"worker:1"到"worker:8",尽管只调用了一次函数(:

thread 'actix-rt:worker:1' panicked at 'called `Result::unwrap()` 
on an `Err` value: Error(BlockingClientInFutureContext, 
"https://www.example.com/")', src/libcore/result.rs:999:5
Panic in Arbiter thread, shutting down system.

谷歌没有在"BlockingClientInFutureContext">上找到任何有用的东西,但我猜它与async/await或Tokio自己的未来有关?

感谢您提供有关阅读内容的任何指示。另外,我是 Rust 的新手。

处理程序函数从 Actix-Web HTttpServer 调用

HttpServer::new(|| App::new().service(
web::resource("/testing").route(
web::get().to(views::testing)
)
)).bind("127.0.0.1:8001")?.run()

我也有类似的问题。对我来说,解决方案是将 Reqwest 板条箱版本锁定在您的货物文件中的 0.9.17,然后重建。

reqwest = "=0.9.17"

看起来较新版本的Reqwest被Actix-web破坏了,除非您在两者上使用异步功能。供参考: https://github.com/seanmonstar/reqwest/issues/541

事实证明,actix_web::web::block()是正确的猜测。使用它可以使进行阻止呼叫成为可能。block()返回一个 Future 在网络请求返回数据后解析。非常靠近JS中的承诺,加上那里的.from_err()

pub fn testing(_req: actix_web::HttpRequest)
-> impl Future<Item = HttpResponse, Error = Error>
{
println!(">>> testing request begin");
let url = Url::parse("https://example.com/").unwrap();
println!(">>> testing url built");
let req = reqwest::Client::new().get(url);
println!(">>> testing req prepared");
actix_web::web::block(move || {
println!(">>> testing res received");
req.send()
})
.from_err()
.and_then(|res| {
println!(">>> testing res: {:?}", &res);
HttpResponse::Ok().content_type("text/html").body("Hello!")
})
}

此外,在main.rs必须使用.to_async()而不是简单地调用.to()路由:

HttpServer::new(|| App::new().service(
web::resource("/testing").route(
web::get().to_async(views::testing)
)
)).bind("127.0.0.1:8001")?.run()

TL;DR:升级到 0.9.22 或更高版本。

该错误表示您正在尝试从异步上下文内部进行阻止网络调用(Actix Web 处理程序是异步调用的(。这在 reqwest 版本 0.9.17 - 0.9.21 中不受支持。

从 0.9.22 开始,作者已经删除了此错误,以支持警告。欲了解更多信息:

https://github.com/seanmonstar/reqwest/pull/670

https://github.com/seanmonstar/reqwest/issues/541

unwrap()的调用失败,因为返回了错误。 最好避免在生产代码中unwrap(),因为这通常意味着我们试图查看"所需"值(通常称为"快乐路径"(,而忽略错误路径。

此代码有效:

use actix_web;
use reqwest::Url;
fn main()  {
println!(">>> testing request begin");
let url = Url::parse("http:/example.com/").unwrap();
println!(">>> testing url built");
let req = reqwest::Client::new().post(url);
println!(">>> testing req prepared");
let res_struct = req.send();
println!(">>> testing res_struct received");
match res_struct {
Ok(r)=> println!("response: {:?}", r),
Err(e)=> println!("error: {}", e),
}
//    let res = res_struct.unwrap();
println!("done.");
}

输出为:

Finished dev [unoptimized + debuginfo] target(s) in 2.63s
Running `target/debug/untitled`
>>> testing request begin
>>> testing url built
>>> testing req prepared
>>> testing res_struct received
error: http://example.com/: error trying to connect: failed to lookup address information: nodename nor servname provided, or not known
>>> testing res unwrapped
done.

上面的代码在没有紧急情况的情况下工作,但example.com的服务器没有提供良好的响应。 如果我使用有效的 URL(例如 https://cisco.com(重新运行它,则不会收到任何错误:

>>> testing request begin
>>> testing url built
>>> testing req prepared
>>> testing res_struct received
response: Response { url: "https://www.cisco.com/", status: 200, headers: {"server": "Apache", "etag": ""1732e-59058880c8465"", "accept-ranges": "bytes", "strict-transport-security": "max-age=31536000", "cdchost": "wemxweb-publish-prod2-02", "x-xss-protection": "1; mode=block", "x-test-debug": "nURL=www.cisco.com,realm=0,isRealm=0,realmDomain=0,shortrealm=0", "content-security-policy": "upgrade-insecure-requests; frame-ancestors *.cisco.com *.jasper.com *.ciscospark.com *.ciscolive.com  http://cisco.lookbookhq.com https://cisco.lookbookhq.com testcisco.marketing.adobe.com cisco.marketing.adobe.com ciscosales.my.salesforce.com test.salesforce.com zedo.com hindustantimes.com economictimes.indiatimes.com *.webex.com *.cdw.com *.cdwg.com *.cdw.ca *.meraki-go.com http://ciscopartners.lookbookhq.com https://ciscopartners.lookbookhq.com ciscolearningsystem.com ciscocustomer.lookbookhq.com cisco.lookbookhq.com;", "content-type": "text/html", "expires": "Sun, 18 Aug 2019 12:10:23 GMT", "cache-control": "max-age=0, no-cache, no-store", "pragma": "no-cache", "date": "Sun, 18 Aug 2019 12:10:23 GMT", "connection": "keep-alive", "vary": "Accept-Encoding"} }
>>> testing res unwrapped
done.

最新更新