[英]How to have a connection with lazy static to S3 from Rust?
我正在嘗試將我們的一個 Python lambda 函數復制到 Rust,但一開始就被 S3 的客戶端卡住了。
在 Python 中很簡單,在 Lambda 初始化期間我聲明了一個變量。 然而,當使用 Rust 時,它有點復雜。
作為 Rust 的新手,在 lazy_static 設置中處理異步是很困難的。
use aws_config::meta::region::RegionProviderChain;
use aws_config::SdkConfig;
use aws_sdk_s3::Client as S3Client;
use lambda_http::Error as LambdaHttpError;
use lambda_http::{run, service_fn, Body, Error, Request, Response};
use lazy_static::lazy_static;
async fn connect_to_s3() -> S3Client {
let region_provider: RegionProviderChain =
RegionProviderChain::default_provider().or_else("eu-west-1");
let config = aws_config::load_from_env().await;
let client: S3Client = S3Client::new(&config);
client
}
lazy_static! {
static ref S3_CLIENT: S3Client = connect_to_s3();
}
這會引發以下錯誤:
error[E0308]: mismatched types
--> src/bin/lambda/rora.rs:20:38
|
20 | static ref S3_CLIENT: S3Client = connect_to_s3();
| -------- ^^^^^^^^^^^^^^^ expected struct `aws_sdk_s3::Client`, found opaque type
| |
| expected `aws_sdk_s3::Client` because of return type
|
note: while checking the return type of the `async fn`
--> src/bin/lambda/rora.rs:10:29
|
10 | async fn connect_to_s3() -> S3Client {
| ^^^^^^^^ checked the `Output` of this `async fn`, found opaque type
= note: expected struct `aws_sdk_s3::Client`
found opaque type `impl Future<Output = aws_sdk_s3::Client>`
help: consider `await`ing on the `Future`
|
20 | static ref S3_CLIENT: S3Client = connect_to_s3().await;
| ++++++
如何在 lambda 設置期間初始化與 s3 的連接?
在查看了 github 上的一堆代碼並與我認識的一些 Rust 開發人員交談后,這里是我所知道的當前最佳選擇:
use async_once::AsyncOnce;
use lazy_static::lazy_static;
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_glue::Client as GlueClient;
use aws_sdk_s3::Client as S3Client;
lazy_static! {
static ref S3_CLIENT: AsyncOnce<S3Client> = AsyncOnce::new(async {
let region_provider = RegionProviderChain::default_provider().or_else("eu-west-1");
let config = aws_config::from_env().region(region_provider).load().await;
S3Client::new(&config)
});
static ref GLUE_CLIENT: AsyncOnce<GlueClient> = AsyncOnce::new(async {
let region_provider = RegionProviderChain::default_provider().or_else("eu-west-1");
let config = aws_config::from_env().region(region_provider).load().await;
GlueClient::new(&config)
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.