在Cloudwatch中搜索带名称的警报

时间:2015-12-23 11:01:52

标签: aws-sdk amazon-cloudwatch

是否可以使用Java API搜索警报或检查CloudWatch中是否已存在警报?

我目前正在这样做,但对我来说看起来并不乐观。

    long offsetInMilliseconds = 1000 * 60 * 60 * 24;
    Dimension instanceDimension = new Dimension();
    instanceDimension.setName("InstanceId");
        instanceDimension.setValue("i-201cb891");

    //Check is Alarms with name exist.
    GetMetricStatisticsRequest getMetricStatisticsRequest  = new GetMetricStatisticsRequest()
            .withStartTime(new Date(new Date().getTime() - offsetInMilliseconds))
            .withNamespace("AWS/EC2")
            .withPeriod(60 * 60)
            .withMetricName("StatusCheckFailed")
            .withStatistics("Average")
            .withDimensions(Arrays.asList(instanceDimension))
            .withEndTime(new Date());

    GetMetricStatisticsResult getMetricStatisticsResult = cloudWatch.getMetricStatistics(getMetricStatisticsRequest);
    System.out.println("" + getMetricStatisticsResult.getDatapoints().size());
    if(getMetricStatisticsResult.getDatapoints().size() == 0) {
        PutMetricAlarmRequest request = new PutMetricAlarmRequest()
                .withActionsEnabled(true).withAlarmName("i-201cb891")
                .withComparisonOperator(ComparisonOperator.GreaterThanOrEqualToThreshold)
                .withDimensions(Arrays.asList(instanceDimension))
               // .withAlarmActions(getTopicARN())
                .withEvaluationPeriods(1)
                .withPeriod(60)
                .withThreshold(60.0D)
                .withStatistic(Statistic.Average)
                .withMetricName("StatusCheckFailed")
                .withNamespace("AWS/EC2");
        cloudWatch.putMetricAlarm(request);
        System.out.println("Alarm created for Instance with ID :  " + "i-201cb891");
    }else{
        System.out.println("Alarm exists with name : " + "i-201cb891");
    }

1 个答案:

答案 0 :(得分:1)

您可以使用AmazonCloudWatch界面查询警报。

来自AmazonCloudWatch API:

DescribeAlarmsResult describeAlarms(DescribeAlarmsRequest describeAlarmsRequest)

您可以使用此方法按名称或前缀查询警报。

以下代码段显示了如何使用API​​:

...

AmazonCloudWatch client = new AmazonCloudWatchClient(new ProfileCredentialsProvider());

DescribeAlarmsRequest request = new DescribeAlarmsRequest();

List<String> alarmNames = new ArrayList<String>();
alarmNames.add("alarmName1");
alarmNames.add("alarmName2");

request.setAlarmNames(alarmNames);

DescribeAlarmsResult result = client.describeAlarms(request);

List<MetricAlarm> alarms = result.getMetricAlarms();

for (MetricAlarm alarm : alarms) {
    System.out.println(alarm.getAlarmName());
}

...

AWS SDK for Java API Reference - 1.10.43