gpt4 book ai didi

java - 如何通过 JAVA API 获取 AWS Billing 指标

转载 作者:行者123 更新时间:2023-11-30 08:41:05 24 4
gpt4 key购买 nike

我发现 AWS 云监视收集计费指标,但找不到任何 api 引用来以编程方式使用它们。我希望它们像卷指标、实例指标一样作为指标,但不是 S3 存储桶中的 CSV 格式。有什么办法可以实现吗?

最佳答案

首先要记住两点:

  1. 根据 this文档中,单个 GetMetricStatistics 请求返回的最大数据点数为 1,440。因此,例如,您不能在 5 分钟内查询一周的数据(因为这将是 2,016 个数据点)。
  2. 要获取计费指标,您可以请求所有服务的预估费用总额或每项服务的预估费用。如前所述here .

此 Java 8 示例以十二小时为周期检索过去两周所有服务的预估费用总额。

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient;
import com.amazonaws.services.cloudwatch.model.Datapoint;
import com.amazonaws.services.cloudwatch.model.Dimension;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsRequest;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsResult;
import java.util.Collections;
import java.util.Date;

public class AWSCloudWatchBillingService {

public static void main(String[] args) {
final String awsAccessKey = "<YOUR_AWS_ACCESS_KEY>";
final String awsSecretKey = "<YOUR_AWS_SECRET_ACCESS_KEY>";

final AmazonCloudWatchClient client = client(awsAccessKey, awsSecretKey);
final GetMetricStatisticsRequest request = request();
final GetMetricStatisticsResult result = result(client, request);
printIt(result);
}

private static AmazonCloudWatchClient client(final String awsAccessKey, final String awsSecretKey) {
final AmazonCloudWatchClient client = new AmazonCloudWatchClient(new BasicAWSCredentials(awsAccessKey, awsSecretKey));
client.setEndpoint("http://monitoring.us-east-1.amazonaws.com/");
return client;
}

private static GetMetricStatisticsRequest request() {
final long twoWeeks = 1000 * 60 * 60 * 24 * 15;
final int twelveHours = 60 * 60 * 12;
return new GetMetricStatisticsRequest()
.withStartTime(new Date(new Date().getTime() - twoWeeks))
.withNamespace("AWS/Billing")
.withPeriod(twelveHours)
.withDimensions(new Dimension().withName("Currency").withValue("USD"))
.withMetricName("EstimatedCharges")
.withStatistics("Average", "Maximum")
.withEndTime(new Date());
}

private static GetMetricStatisticsResult result(
final AmazonCloudWatchClient client, final GetMetricStatisticsRequest request) {
return client.getMetricStatistics(request);
}

private static void printIt(final GetMetricStatisticsResult result) {
Collections.sort(result.getDatapoints(), (Datapoint dp1, Datapoint dp2) -> dp1.getTimestamp().compareTo(dp2.getTimestamp()));
System.out.println("**************************************");
System.out.println(result);
}
}

关于java - 如何通过 JAVA API 获取 AWS Billing 指标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35293852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com