问题描述

在Azure上创建虚拟机(VM)后,在门户上可以查看监控指标(Metrics),如CPU Usage,Memory,Disk I/O等。那如何通过Java 代码获取到这些指标呢?

解决办法

方式一:使用REST API

Azure中门户上看见的内容都是通过REST API来获取值,基于此原理,可以通过在门户中Metrics页面中,点看CPU的指标数据后,通过F12(开发者工具),查看具体使用的是什么API, 并参考同样的方式在Java 代码中调用该类接口来完成。

【Azure Developer】通过Azure提供的Azue Java JDK 查询虚拟机的CPU使用率和内存使用率-LMLPHP

通常情况,是可以在Azure Monitor官网中(https://docs.microsoft.com/zh-cn/rest/api/monitor/)找到需要的REST API接口。如:

方式二:使用Azure VM诊断日志 ——> Storage Table——> Java Code (Storage SDK)

开启虚拟机的诊断日志,让Azure VM把监控数据发送到Storage Table中,通过Storage SDK直接获取Table中的数据。

开启诊断日志

【Azure Developer】通过Azure提供的Azue Java JDK 查询虚拟机的CPU使用率和内存使用率-LMLPHP

获取Storage Table中数据的Java代码

参考资料


REST API 引用 Azure Monitor: https://docs.microsoft.com/zh-cn/rest/api/monitor/

如何通过 Java 使用 Azure 表存储或 Azure Cosmos DB 表 API: https://docs.azure.cn/zh-cn/cosmos-db/table-storage-how-to-use-java?toc=https%3A%2F%2Fdocs.azure.cn%2Fzh-cn%2Fstorage%2Ftables%2Ftoc.json&bc=https%3A%2F%2Fdocs.azure.cn%2Fzh-cn%2Fbread%2Ftoc.json

附录一:查看Azure REST API的方法

【Azure Developer】通过Azure提供的Azue Java JDK 查询虚拟机的CPU使用率和内存使用率-LMLPHP

附录二:使用Java SDK直接获取VM对象和VM对象中Mertics的代码https://github.com/Azure/azure-libraries-for-java/blob/master/azure-mgmt-monitor/src/test/java/com/microsoft/azure/management/monitor/MonitorActivityAndMetricsTests.java

/**
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 */

package com.microsoft.azure.management.monitor;

import com.microsoft.azure.PagedList;
import com.microsoft.azure.management.compute.VirtualMachine;
import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;

import java.util.List;

public class MonitorActivityAndMetricsTests extends MonitorManagementTest {
    @Test
    public void canListEventsAndMetrics() throws Exception {
        DateTime recordDateTime = SdkContext.dateTimeNow().minusDays(40);
        VirtualMachine vm = computeManager.virtualMachines().list().get(0);

        // Metric Definition
        List<MetricDefinition> mt = monitorManager.metricDefinitions().listByResource(vm.id());

        Assert.assertNotNull(mt);
        MetricDefinition mDef = mt.get(0);
        Assert.assertNotNull(mDef.metricAvailabilities());
        Assert.assertNotNull(mDef.namespace());
        Assert.assertNotNull(mDef.supportedAggregationTypes());

        // Metric
        MetricCollection metrics = mDef.defineQuery()
                .startingFrom(recordDateTime.minusDays(30))
                .endsBefore(recordDateTime)
                .withResultType(ResultType.DATA)
                .execute();

        Assert.assertNotNull(metrics);
        Assert.assertNotNull(metrics.namespace());
        Assert.assertNotNull(metrics.resourceRegion());
        Assert.assertEquals("Microsoft.Compute/virtualMachines", metrics.namespace());
12-13 01:01