我第一次在java中使用aws api来获取我的ec2实例的云监视统计信息。我用谷歌搜索了这个,找到了一些代码片段。在这里
AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(
new BasicAWSCredentials(AccessKey, SecretKey));
cloudWatch.setEndpoint("ec2-<my-static-ip>.compute-1.amazonaws.com");
long offsetInMilliseconds = 1000 * 60 * 60 * 24;
Dimension instanceDimension = new Dimension();
instanceDimension.setName("Instanceid");
instanceDimension.setValue(InstanceId);
GetMetricStatisticsRequest request = new GetMetricStatisticsRequest()
.withStartTime(
new Date(new Date().getTime()
- offsetInMilliseconds))
.withNamespace("AWS/EC2")
.withPeriod(60 * 60)
.withDimensions(
new Dimension().withName("InstanceId").withValue(
InstanceId))
.withMetricName("CPUUtilization")
.withStatistics("Average", "Maximum")
.withEndTime(new Date());
GetMetricStatisticsResult getMetricStatisticsResult = cloudWatch
.getMetricStatistics(request);
double avgCPUUtilization = 0;
List dataPoint = getMetricStatisticsResult.getDatapoints();
for (Object aDataPoint : dataPoint) {
Datapoint dp = (Datapoint) aDataPoint;
avgCPUUtilization = dp.getAverage();
System.out.println(InstanceId
+ " instance's average CPU utilization : "
+ dp.getAverage());
}
} catch (AmazonServiceException ase) {
System.out
.println("Caught an AmazonServiceException, which means the request was made "
+ "to Amazon EC2, but was rejected with an error response for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
}
因此,使用此代码我尝试获取统计信息,但第一次它会抛出错误
com.amazonaws.AmazonClientException: Unable to execute HTTP request:Connection to https://ec2-<my-static-ip>.compute-1.amazonaws.com refused
然后我以为它正在发送 https 请求。所以我在我的实例上启用了 ssl 并尝试了,然后我遇到了异常。
com.amazonaws.AmazonClientException: Unable to execute HTTP request: peer not authenticated
我在我的实例中使用 OpenJDK,所以我认为这可能会导致问题。然后我删除了 openjdk 并安装了 Oracle JDK 1.7。但仍然是同样的问题。
我的问题是,
1) 如何仅发送 HTTP(而不是 HTTPS)请求来获取统计信息?
2)如何摆脱这个问题,以便我可以获得结果?
但是请不要让我阅读任何文档,因为我在网络、博客、论坛、文档等中搜索搞砸了,然后我就到了这里。所以,请为我提供解决方案或告诉我哪里出了问题。
有人可以帮我解决这个问题吗?
提前谢谢您。
最佳答案
找到解决方案。
1) 删除了 AmazonCloudWatchClient 的设置端点。
2) AWS 凭证存在问题(访问 key ID、 key )。因此,我创建了另一组凭证并为用户提供了 CloudWatchFullAccess 策略。
现在它就像 Charm 一样工作......:-)
谢谢。
关于java - AmazonCloudWatchClient 不发送 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23404231/