AmazonS3ClientBuilder.defaultClient() 無法考慮地區?

Amazon Java SDK 已将构造函数标记为已弃用,以支持某些 .但是,遵循该建议并不会导致AmazonS3客户端工作相同。特别是,客户端以某种方式未能考虑区域。如果运行以下测试,则测试将演示问题。AmazonS3ClientAmazonS3ClientBuilder.defaultClient()thisFails

public class S3HelperTest {
  @Test
  public void thisWorks() throws Exception {
    AmazonS3 s3Client = new AmazonS3Client();  // this call is deprecated
    s3Client.setS3ClientOptions(S3ClientOptions.builder().setPathStyleAccess(true).build());
    assertNotNull(s3Client);
  }

  @Test
  public void thisFails() throws Exception {
    AmazonS3 s3Client = AmazonS3ClientBuilder.defaultClient();
    /*
     * The following line throws like com.amazonaws.SdkClientException:
     * Unable to find a region via the region provider chain. Must provide an explicit region in the builder or
     * setup environment to supply a region.
     */
    s3Client.setS3ClientOptions(S3ClientOptions.builder().setPathStyleAccess(true).build());
  }
}

com.amazonaws.SdkClientException: Unable to find a region via the region provider chain. Must provide an explicit region in the builder or setup environment to supply a region.
    at com.amazonaws.client.builder.AwsClientBuilder.setRegion(AwsClientBuilder.java:371)
    at com.amazonaws.client.builder.AwsClientBuilder.configureMutableProperties(AwsClientBuilder.java:337)
    at com.amazonaws.client.builder.AwsSyncClientBuilder.build(AwsSyncClientBuilder.java:46)
    at com.amazonaws.services.s3.AmazonS3ClientBuilder.defaultClient(AmazonS3ClientBuilder.java:54)
    at com.climate.tenderfoot.service.S3HelperTest.thisFails(S3HelperTest.java:21)
    ...

这是 AWS 开发工具包错误吗?是否有一些“区域默认提供程序链”或某种机制从环境中派生区域并将其设置为客户端?替换弃用的方法不会导致相同的功能,这似乎真的很弱。


答案 1

看起来生成器需要一个区域。可能这个线程是相关的(我会在第3行中使用):.withRegion(Regions.US_EAST_1)

要模拟之前的行为(未配置区域),您还需要在客户端构建器中启用“强制全局存储桶访问”:

AmazonS3 client = 
        AmazonS3ClientBuilder.standard()
                             .withRegion("us-east-1") // The first region to try your request against
                             .withForceGlobalBucketAccess(true) // If a bucket is in a different region, try again in the correct region
                             .build();

这将禁止显示您收到的异常,并自动重试异常中区域下的请求。它在生成器中是显式的,因此您可以了解此跨区域行为。注意:SDK 将在第一次失败后缓存存储桶区域,因此针对此存储桶的每个请求不必发生两次。


另外,如果您想使用AWS文档,则需要具有~/.aws/credentials和~/.aws/config文件AmazonS3ClientBuilder.defaultClient();

~/.aws/凭证内容:

[default]
aws_access_key_id = your_id
aws_secret_access_key = your_key

~/.aws/config contents:

[default]
region = us-west-1

在同一 AWS 文档页面中,如果您不想对区域/凭证进行硬编码,则可以按照通常的方式将其作为 Linux 计算机中的环境变量:

export AWS_ACCESS_KEY_ID=your_access_key_id
export AWS_SECRET_ACCESS_KEY=your_secret_access_key
export AWS_REGION=your_aws_region

答案 2
    BasicAWSCredentials creds = new BasicAWSCredentials("key_ID", "Access_Key");
    AWSStaticCredentialsProvider provider = new 
    AWSStaticCredentialsProvider(creds);

    AmazonSQS sqs =AmazonSQSClientBuilder.standard()
    .withCredentials(provider)
    .withRegion(Regions.US_EAST_2)
    .build();

推荐