问题描述
我在尝试使用适用于 Java 的 AWS 开发工具包 v2.x 向现有 CloudFront 资源添加新的备用域名 (CNAME) 时遇到困难
这是我目前使用的代码片段:
// First I get the actual resource from AWS
GetdistributionResponse distributioninformation = cloudFrontclient
.getdistribution(GetdistributionRequest.builder().id(input.getdistributionId())
.build());
// Then I extract the part I want to edit
distributionConfig config = distributioninformation.distribution().distributionConfig();
// so far so good,I'm able to see my data as intended
// The next thing is to try adding the new alias,and of course I can't as that array is Unmodifiable!
// Meaning that I'm always getting an: java.lang.UnsupportedOperationException
config.aliases().items().add(input.getAlternativeDomain());
// If the prevIoUs line worked or I find an alternative solution I'm planning to make the following update request
UpdatedistributionRequest updatedistributionRequest = UpdatedistributionRequest
.builder()
.distributionConfig(config)
.build();
cloudFrontclient.updatedistribution(updatedistributionRequest);
我有点迷茫,我不确定这应该如何工作。
我会很感激我能得到的任何帮助
提前致谢
解决方法
我确认当您使用从 distributionConfig
返回的对象时,属于 DistributionConfig 的方法 - 甚至注释 - 似乎是只读的 Distribution disObject = response.distribution();
DistributionConfig config = disObject.distributionConfig();
解决方案是使用 builder 方法创建一个新的 DistributionConfig 对象(见下文)。添加新值,然后还读入未更改的值。否则抛出 Java 异常。
这里我添加了一个新注释作为修改分发的示例。
public static void main(String[] args) {
CloudFrontClient cloudFrontClient = CloudFrontClient.builder()
.region(Region.AWS_GLOBAL)
.build();
try {
// Lets get the Distribution to modify
GetDistributionRequest disRequest = GetDistributionRequest.builder()
.id("E90U7J6Pxxxxx")
.build();
GetDistributionResponse response = cloudFrontClient.getDistribution(disRequest);
Distribution disObject = response.distribution();
DistributionConfig config = disObject.distributionConfig();
// Create a new DistributionConfig object and add new values to comment and aliases
DistributionConfig config1 = DistributionConfig.builder()
.aliases(config.aliases()) // You can pass in new values here
.comment("New Comment")
.cacheBehaviors(config.cacheBehaviors())
.priceClass(config.priceClass())
.defaultCacheBehavior(config.defaultCacheBehavior())
.enabled(config.enabled())
.callerReference(config.callerReference())
.logging(config.logging())
.originGroups(config.originGroups())
.origins(config.origins())
.restrictions(config.restrictions())
.defaultRootObject(config.defaultRootObject())
.webACLId(config.webACLId())
.httpVersion(config.httpVersion())
.viewerCertificate(config.viewerCertificate())
.customErrorResponses(config.customErrorResponses())
.build();
UpdateDistributionRequest updateDistributionRequest = UpdateDistributionRequest.builder()
.distributionConfig(config1)
.id(disObject.id())
.ifMatch(response.eTag())
.build();
cloudFrontClient.updateDistribution(updateDistributionRequest);
} catch (CloudFrontException e){
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
}
这行得通,您可以看到新评论: