我在使用 AmazonCloudWatch 获取 CPU 利用率时遇到了一点问题。当我尝试使用 AmazonCloudWatch.GetMetricStatistics() 时,我收到一条异常消息:
引发了“Amazon.CloudWatch.AmazonCloudWatchException”类型的异常。
这是一个内部异常:
{“远程服务器返回错误:(400) 错误请求。”}
这是我用来拨打电话的代码:
public static String getCPUStats(String Endpoint, String InstanceID)
{
try
{
AmazonCloudWatchConfig cloudConfig = new AmazonCloudWatchConfig();
cloudConfig.ServiceURL = Endpoint;
string AWSAccessKey = Sql.ToString(appConfig["AWSAccessKey"]);
string AWSSecretKey = Sql.ToString(appConfig["AWSSecretKey"]);
AmazonCloudWatch client = AWSClientFactory.CreateAmazonCloudWatchClient(AWSAccessKey, AWSSecretKey, cloudConfig);
GetMetricStatisticsRequest request = new GetMetricStatisticsRequest();
request.Dimensions.Add(new Dimension { Name = "InstanceId", Value = InstanceID });
request.StartTime = DateTime.UtcNow.AddMinutes(-5);
request.EndTime = DateTime.UtcNow;
request.Namespace = "AWS/EC2";
request.Statistics.Add("Maximum");
request.Statistics.Add("Average");
request.MetricName = "CPUUtilization";
request.Period = 60;
GetMetricStatisticsResponse r = client.GetMetricStatistics(request);
if (r.GetMetricStatisticsResult.Datapoints.Count > 0)
{
Datapoint dataPoint = r.GetMetricStatisticsResult.Datapoints[0];
return "CPU maximum load: " + dataPoint.Maximum;
}
return "No data available.";
}
catch (Exception ex)
{
return ex.Message;
}
}
一些旁注 - 访问密钥、秘密访问密钥和端点可以很好地创建 AmazonEC2Client,所以我很确定问题不存在。
我已经做了很多谷歌搜索和研究文档,但没有成功解决这个问题。有任何想法吗?非常感谢!