我正在使用actix_web和rusoto_s3编写一个应用程序。
当我从main直接在actix请求之外运行一个命令时,它运行得很好,并且get_object按照预期工作。当这被封装在actix_web请求中时,流将永远被阻塞。
我有一个为所有请求共享的客户机,它被封装到一个Arc中(这发生在actix数据内部)。
完整代码:
fn index(
_req: HttpRequest,
path: web::Path<String>,
s3: web::Data<S3Client>,
) -> impl Future<Item = HttpResponse, Error = actix_web::Error> {
s3.get_object(GetObjectRequest {
bucket: "my_bucket".to_owned(),
key: path.to_owned(),
..Default::default()
})
.and_then(move |res| {
info!("Response {:?}", res);
let mut stream = res.body.unwrap().into_blocking_read();
let mut body = Vec::new();
stream.read_to_end(&mut body).unwrap();
match process_file(body.as_slice()) {
Ok(result) => Ok(result),
Err(error) => Err(RusotoError::from(error)),
}
})
.map_err(|e| match e {
RusotoError::Service(GetObjectError::NoSuchKey(key)) => {
actix_web::error::ErrorNotFound(format!("{} not found", key))
}
error => {
error!("Error: {:?}", error);
actix_web::error::ErrorInternalServerError("error")
}
})
.from_err()
.and_then(move |img| HttpResponse::Ok().body(Body::from(img)))
}
fn health() -> HttpResponse {
HttpResponse::Ok().finish()
}
fn main() -> std::io::Result<()> {
let name = "rust_s3_test";
env::set_var("RUST_LOG", "debug");
pretty_env_logger::init();
let sys = actix_rt::System::builder().stop_on_panic(true).build();
let prometheus = PrometheusMetrics::new(name, "/metrics");
let s3 = S3Client::new(Region::Custom {
name: "eu-west-1".to_owned(),
endpoint: "http://localhost:9000".to_owned(),
});
let s3_client_data = web::Data::new(s3);
Server::build()
.bind(name, "0.0.0.0:8080", move || {
HttpService::build().keep_alive(KeepAlive::Os).h1(App::new()
.register_data(s3_client_data.clone())
.wrap(prometheus.clone())
.wrap(actix_web::middleware::Logger::default())
.service(web::resource("/health").route(web::get().to(health)))
.service(web::resource("/{file_name}").route(web::get().to_async(index))))
})?
.start();
sys.run()
}在stream.read_to_end中,线程被阻塞,并且从未被解析。
我尝试过在每个请求中克隆客户机,并在每个请求中创建一个新的客户机,但在所有场景中都得到了相同的结果。
我做错了什么吗?
如果我不使用异步.
s3.get_object(GetObjectRequest {
bucket: "my_bucket".to_owned(),
key: path.to_owned(),
..Default::default()
})
.sync()
.unwrap()
.body
.unwrap()
.into_blocking_read();
let mut body = Vec::new();
io::copy(&mut stream, &mut body);这是Tokio的问题吗?
发布于 2019-07-03 09:16:54
let mut stream = res.body.unwrap().into_blocking_read();检查into_blocking_read():它调用.wait()。您不应该在Future中调用阻塞代码。
由于Rusoto的body是一个Stream,所以有一种异步读取它的方法:
.and_then(move |res| {
info!("Response {:?}", res);
let stream = res.body.unwrap();
stream.concat2().map(move |file| {
process_file(&file[..]).unwrap()
})
.map_err(|e| RusotoError::from(e)))
})process_file不应该阻止封闭的Future。如果需要阻塞,您可以考虑在新线程上运行它,或者使用blocking封装它。
注意:您可以在您的实现中使用tokio_ blocking的blocking,但我建议您首先了解它的工作原理。
如果不打算将整个文件加载到内存中,则可以使用for_each。
stream.for_each(|part| {
//process each part in here
//Warning! Do not add blocking code here either.
})还请参见:
https://stackoverflow.com/questions/56846492
复制相似问题