如何有一个连接与懒惰静态到S3从 rust ?

kqqjbcuj  于 2022-12-26  发布在  其他
关注(0)|答案(1)|浏览(139)

我试图将我们的一个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的连接?

olhwl3o2

olhwl3o21#

在回顾了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)
    });
}

相关问题