将 GetMetricData 与 Amazon SDK 或 CLI 配合使用 - Amazon CloudWatch
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

GetMetricData 与 Amazon SDK 或 CLI 配合使用

以下代码示例演示如何使用 GetMetricData

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

/// <summary> /// Get data for CloudWatch metrics. /// </summary> /// <param name="minutesOfData">The number of minutes of data to include.</param> /// <param name="useDescendingTime">True to return the data descending by time.</param> /// <param name="endDateUtc">The end date for the data, in UTC.</param> /// <param name="maxDataPoints">The maximum data points to include.</param> /// <param name="dataQueries">Optional data queries to include.</param> /// <returns>A list of the requested metric data.</returns> public async Task<List<MetricDataResult>> GetMetricData(int minutesOfData, bool useDescendingTime, DateTime? endDateUtc = null, int maxDataPoints = 0, List<MetricDataQuery>? dataQueries = null) { var metricData = new List<MetricDataResult>(); // If no end time is provided, use the current time for the end time. endDateUtc ??= DateTime.UtcNow; var timeZoneOffset = TimeZoneInfo.Local.GetUtcOffset(endDateUtc.Value.ToLocalTime()); var startTimeUtc = endDateUtc.Value.AddMinutes(-minutesOfData); // The timezone string should be in the format +0000, so use the timezone offset to format it correctly. var timeZoneString = $"{timeZoneOffset.Hours:D2}{timeZoneOffset.Minutes:D2}"; var paginatedMetricData = _amazonCloudWatch.Paginators.GetMetricData( new GetMetricDataRequest() { StartTimeUtc = startTimeUtc, EndTimeUtc = endDateUtc.Value, LabelOptions = new LabelOptions { Timezone = timeZoneString }, ScanBy = useDescendingTime ? ScanBy.TimestampDescending : ScanBy.TimestampAscending, MaxDatapoints = maxDataPoints, MetricDataQueries = dataQueries, }); await foreach (var data in paginatedMetricData.MetricDataResults) { metricData.Add(data); } return metricData; }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 GetMetricData

Java
SDK for Java 2.x
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

public static void getCustomMetricData(CloudWatchClient cw, String fileName) { try { // Read values from the JSON file. JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); // Set the date. Instant nowDate = Instant.now(); long hours = 1; long minutes = 30; Instant date2 = nowDate.plus(hours, ChronoUnit.HOURS).plus(minutes, ChronoUnit.MINUTES); Metric met = Metric.builder() .metricName(customMetricName) .namespace(customMetricNamespace) .build(); MetricStat metStat = MetricStat.builder() .stat("Maximum") .period(1) .metric(met) .build(); MetricDataQuery dataQUery = MetricDataQuery.builder() .metricStat(metStat) .id("foo2") .returnData(true) .build(); List<MetricDataQuery> dq = new ArrayList<>(); dq.add(dataQUery); GetMetricDataRequest getMetReq = GetMetricDataRequest.builder() .maxDatapoints(10) .scanBy(ScanBy.TIMESTAMP_DESCENDING) .startTime(nowDate) .endTime(date2) .metricDataQueries(dq) .build(); GetMetricDataResponse response = cw.getMetricData(getMetReq); List<MetricDataResult> data = response.metricDataResults(); for (MetricDataResult item : data) { System.out.println("The label is " + item.label()); System.out.println("The status code is " + item.statusCode().toString()); } } catch (CloudWatchException | IOException e) { System.err.println(e.getMessage()); System.exit(1); } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 GetMetricData

Kotlin
适用于 Kotlin 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

suspend fun getCustomMetricData(fileName: String) { // Read values from the JSON file. val parser = JsonFactory().createParser(File(fileName)) val rootNode = ObjectMapper().readTree<JsonNode>(parser) val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText() val customMetricName = rootNode.findValue("customMetricName").asText() // Set the date. val nowDate = Instant.now() val hours: Long = 1 val minutes: Long = 30 val date2 = nowDate.plus(hours, ChronoUnit.HOURS).plus( minutes, ChronoUnit.MINUTES, ) val met = Metric { metricName = customMetricName namespace = customMetricNamespace } val metStat = MetricStat { stat = "Maximum" period = 1 metric = met } val dataQUery = MetricDataQuery { metricStat = metStat id = "foo2" returnData = true } val dq = ArrayList<MetricDataQuery>() dq.add(dataQUery) val getMetReq = GetMetricDataRequest { maxDatapoints = 10 scanBy = ScanBy.TimestampDescending startTime = aws.smithy.kotlin.runtime.time .Instant(nowDate) endTime = aws.smithy.kotlin.runtime.time .Instant(date2) metricDataQueries = dq } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.getMetricData(getMetReq) response.metricDataResults?.forEach { item -> println("The label is ${item.label}") println("The status code is ${item.statusCode}") } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 GetMetricData

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将 CloudWatch 与 Amazon SDK 结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。