Amazon Java SDK已将AmazonS3Client
的构造器标记为弃用,转而支持某些AmazonS3ClientBuilder.defaultClient()
。但是,遵循该建议并不会产生工作相同的AmazonS3客户端。特别是,客户端不知何故未能考虑区域。如果您运行下面的测试,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 SDK Bug吗?是否有某种“区域缺省提供商链”或某种机制来从环境中派生区域并将其设置到客户端?替换弃用的方法没有产生相同的功能,这似乎真的很弱。
发布于 2017-10-12 05:04:26
看起来生成器需要一个区域。this thread可能是相关的(我会在第三行使用.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 documentation中,如果要使用AmazonS3ClientBuilder.defaultClient();
,则需要有~/.aws/credentials和~/.aws/config文件
~/.aws/凭据内容:
[default]
aws_access_key_id = your_id
aws_secret_access_key = your_key
~/.aws/config内容:
[default]
region = us-west-1
在同一个AWS documentation页面中,如果你不想硬编码区域/凭证,你可以用通常的方法将它作为环境变量放在你的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
发布于 2019-04-07 12:24:45
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();
发布于 2019-07-08 14:41:24
在.aws下创建名为"config“的文件。并放在内容下方。
~/.aws/config内容:
[default]
region = us-west-1
output = json
https://stackoverflow.com/questions/46697047
复制相似问题