如何在ListMetrics函数中使用nextToken

本文关键字:nextToken 函数 ListMetrics | 更新日期: 2023-09-27 18:14:41

我试图使用函数:ListMetrics列出存储在CloudWatch中的所有指标。该函数返回大约500个指标和一个名为NextToken的字符串值,该值将在下一次调用中用于获取其余指标。

这是我下面的代码,但我不知道如何使用NextToken来获得其余的指标。

  // creates the CloudWatch client
            var cw = Amazon.AWSClientFactory.CreateAmazonCloudWatchClient(Amazon.RegionEndpoint.EUWest1);
        // initialses the list metrics request
        ListMetricsRequest lmr = new ListMetricsRequest();
        ListMetricsResponse lmresponse = cw.ListMetrics(lmr);

        // loop that uses the token to get all the metrics available
        // not finished yet
        do
        {
            lmresponse = cw.ListMetrics(lmr);
            lmresponse.NextToken;
        } while (lmresponse.NextToken != null);

我想知道如何使用NextToken以获得其余的指标。不幸的是,我在网上找不到任何例子。

如何在ListMetrics函数中使用nextToken

如果响应中有一个NextToken,您可以在下一个请求中使用它:

// creates the CloudWatch client
var cw =  Amazon.AWSClientFactory.CreateAmazonCloudWatchClient(Amazon.RegionEndpoint.EUWest1);
// initialses the list metrics request
ListMetricsRequest lmr = new ListMetricsRequest();
ListMetricsResponse lmresponse = cw.ListMetrics(lmr);
while (lmresponse.NextToken != null);
{
    // set request token 
    lmr.NextToken = lmresponse.NextToken;
    lmresponse = cw.ListMetrics(lmr);
    // Process metrics found in lmresponse.Metrics
} 

将其放入do-while循环中确保ListMetrics函数不断被调用并列出所有指标,只要nextToken不为空。

private string nextToken;
do
{
  lmrequest.NextToken = nextToken;
  lmresponse = cloudwatch.ListMetrics(lmrequest);
  nextToken = lmresponse.NextToken;
} while (nextToken != null);

如果你只需要遍历整个指标列表,我会使用foreach循环。代码看起来像这样:

        // creates the CloudWatch client
        var cw = Amazon.AWSClientFactory.CreateAmazonCloudWatchClient(Amazon.RegionEndpoint.EUWest1);
        // initialses the list metrics request
        ListMetricsRequest lmr = new ListMetricsRequest();
        ListMetricsResponse lmresponse = cw.ListMetrics(lmr);
        foreach (Metric metric in lmresponse.Metrics)
        {
            // do something with
            // metric.MetricName;
            // metric.Dimensions;
            // etc
        }