本教程详细介绍如何使用Alibaba Cloud SDK for Java查询指定资源最新的监控数据。

前提条件

在使用本教程前,请确保已完成以下操作:
  • 使用Alibaba Cloud SDK for Java,您需要一个阿里云账号和访问密钥(AccessKey)。 请在阿里云控制台中的AccessKey管理页面上创建和查看您的AccessKey。
  • 确保您已经安装了Alibaba Cloud SDK for Java,准确的SDK版本号,请参见阿里云开发工具包(SDK)
    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.4.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-ecs -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-ecs</artifactId>
            <version>4.17.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-cms -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-cms</artifactId>
            <version>7.0.4</version>
        </dependency>
    </dependencies>

代码示例

本文操作示例主要以代码形式体现,具体代码如下:
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.cms.model.v20190101.DescribeMetricLastRequest;
import com.aliyuncs.cms.model.v20190101.DescribeMetricLastResponse;
import com.aliyuncs.cms.model.v20190101.DescribeProjectMetaRequest;
import com.aliyuncs.cms.model.v20190101.DescribeProjectMetaResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查询指定资源最新的监控数据。
 */
public class DescribeMetricLastDemo {


    /**
     * 获取接入的云产品信息,包括产品的描述信息、 Namespace和标签。
     */
    private DescribeProjectMetaResponse describeProjectMeta(DescribeProjectMetaRequest request, IAcsClient client) {
        try {
            // 调用SDK发送请求
            return client.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
            // 发生调用错误,抛出运行时异常
            throw new RuntimeException();
        }
    }

    /**
     * 查询指定监控对象的最新监控数据。
     */
    private DescribeMetricLastResponse describeMetricLast(DescribeMetricLastRequest request, IAcsClient client) {
        try {
            // 调用SDK发送请求
            return client.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
            // 发生调用错误,抛出运行时异常
            throw new RuntimeException();
        }
    }

    private static void log_print(String methodName, String result) {
        System.out.println("-------------------------------" + methodName + "-------------------------------");
        System.out.println(result);
    }

    // 查询对应产品的namespace
    private static String getValue(List<DescribeProjectMetaResponse.Resource> resourceList, String value) {
        Gson gson = new Gson();
        for (DescribeProjectMetaResponse.Resource resource : resourceList) {
            List list = gson.fromJson(resource.getLabels(), List.class);
            Map map = (Map) list.get(0);
            String productCode = (String) map.get("value");
            if (value.equalsIgnoreCase(productCode)) {
                return resource.getNamespace();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        // 设置鉴权参数,初始化客户端
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-qingdao",// 地域ID
                "your-access-key-id",// 您的AccessKey ID
                "your-access-key-secret");// 您的AccessKey Secret
        IAcsClient client = new DefaultAcsClient(profile);
        Gson gson = new Gson();
        DescribeMetricLastDemo describeMetricLastDemo = new DescribeMetricLastDemo();

        // 查询云产品信息
        DescribeProjectMetaRequest describeProjectMetaRequest = new DescribeProjectMetaRequest();
        describeProjectMetaRequest.setPageNumber(1);
        // 目前接入的云产品共有68个,分页大小设置成100,全部获取
        describeProjectMetaRequest.setPageSize(100);
        DescribeProjectMetaResponse describeProjectMetaResponse = describeMetricLastDemo.describeProjectMeta(describeProjectMetaRequest, client);
        log_print("describeProjectMeta", gson.toJson(describeProjectMetaResponse));

        // 查询对应产品的namespace
        List<DescribeProjectMetaResponse.Resource> resources = describeProjectMetaResponse.getResources();
        String namespace = getValue(resources, "ECS");

        // 查询指定实例最新监控数据
        DescribeMetricLastRequest describeMetricLastRequest = new DescribeMetricLastRequest();
        // 监控指标,CPU利用率
        describeMetricLastRequest.setMetricName("CPUUtilization");
        // 产品命名空间
        describeMetricLastRequest.setNamespace(namespace);
        // 封装dimensions字段,其值为json字符串类型
        List<Map<String, String>> instances = new ArrayList<>();
        Map<String, String> instanceMap = new HashMap<>();
        instanceMap.put("instanceId", "i-m5eimwfzxxxxxxxx3e13o");
        instances.add(instanceMap);
        // 实例筛选条件
        describeMetricLastRequest.setDimensions(gson.toJson(instances));
        DescribeMetricLastResponse describeMetricLastResponse = describeMetricLastDemo.describeMetricLast(describeMetricLastRequest, client);
        log_print("describeMetricLast", gson.toJson(describeMetricLastResponse));
    }
}

运行结果

正确的运行结果类似如下:
-------------------------------describeProjectMeta-------------------------------
{
    "requestId": "CB9F71D3-9C73-4305-863F-FF23C34456E5",
    "success": true,
    "code": "200",
    "total": "68",
    "pageNumber": "1",
    "pageSize": "100",
    "resources": [
        {
            "namespace": "acs_ads",
            "description": "分析型数据库",
            "labels": "[{\"name\":\"product\",\"value\":\"ADS\"},{\"name\":\"productCategory\",\"value\":\"ads,ads_mysql\"},{\"name\":\"groupFlag\",\"value\":\"true\"}]"
        },
        {
            "namespace": "acs_airec",
            "description": "智能推荐",
            "labels": "[{\"name\":\"product\",\"value\":\"AIRec\"},{\"name\":\"productCategory\",\"value\":\"airec\"},{\"name\":\"groupFlag\",\"value\":\"true\"}]"
        },
        {...}
    ]
}
-------------------------------describeMetricLast-------------------------------
{
    "code": "200",
    "requestId": "9E36FA2B-191A-4C4C-A009-C72AD898EB11",
    "datapoints": "[{\"timestamp\":1570501620000,\"userId\":\"123157908552xxxx\",\"instanceId\":\"i-m5eimwfzxxxxxxxx3e13o\",\"Minimum\":1.06,\"Average\":1.06,\"Maximum\":1.06}]",
    "period": "60",
    "success": true
}