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

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介: 【Azure Developer】通过Azure提供的Azue Java JDK 查询虚拟机的CPU使用率和内存使用率

问题描述

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

关于VM 的内存使用率,虚拟机本身并没有提供这个指标,需要开启诊断后去Azure Storage表中获取,字段为\Memory\% Committed Bytes In Use是开启了诊断日志存储到WADMetrics

 

解决办法

方式一:使用REST API

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

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

Metrics - List

列出资源的指标值。

GET https://management.azure.com/{resourceUri}/providers/microsoft.insights/metrics?api-version=2018-01-01

 

在携带相应的参数后的请求URL:

GET https://management.azure.com/{resourceUri}/providers/microsoft.insights/metrics?timespan={timespan}&interval={interval}&metricnames={metricnames}&aggregation={aggregation}&top={top}&orderby={orderby}&$filter={$filter}&resultType={resultType}&api-version=2018-01-01&metricnamespace={metricnamespace}
上文截图中调用通过API获取到的Metrics的URL参数值为:
"/subscriptions/<subscriptionid>/resourceGroups/<resource group>/providers/Microsoft.Compute/virtualMachines/<vm name>/providers/microsoft.Insights/metrics?
timespan=2020-11-24T22:03:01.141Z/2020-11-27T04:55:40.325Z
&interval=PT30M
&metricnames=Percentage CPU
&aggregation=average
&metricNamespace=microsoft.compute%2Fvirtualmachines
&autoadjusttimegrain=true
&validatedimensions=false
&api-version=2019-07-01"

参数的详细说明:

Name In Required Type Description

resourceUri

path True
  • string

资源的标识符。

api-version

query True
  • string

客户端 Api 版本。

$filter

query  
  • string

$filter用于减少返回的指标数据集。

aggregation

query  
  • string

要检索的聚合类型(逗号分隔)的列表。

interval

query  
  • string
duration

查询的间隔(即时粒)。

metricnames

query  
  • string

要检索的指标(逗号分隔)的名称。

metricnamespace

query  
  • string

用于查询指标定义的指标命名空间。

orderby

query  
  • string

用于对结果进行排序的聚合和排序方向。 只能指定一个订单。 示例:总和 asc。

resultType

query  

减少收集的数据集。 允许的语法取决于操作。 有关详细信息,请参阅操作说明。

timespan

query  
  • string

查询的时间跨度。 它是具有以下格式"startDateTime_ISO/endDateTime_ISO"的字符串。

top

query  
  • integer
int32

要检索的最大记录数。 仅在指定$filter时有效。 默认值为 10。

全文内容:https://docs.microsoft.com/zh-cn/rest/api/monitor/metrics/list

 

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

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

开启诊断日志

获取Storage Table中数据的Java代码

检索分区中的所有实体

若要对表查询分区中的实体,可以使用 TableQuery调用 TableQuery.from 可创建针对特定表的查询,该查询将返回指定的结果类型。 以下代码指定了一个筛选器,用于筛选其中的分区键是“Smith”的实体。 TableQuery.generateFilterCondition 是用于创建查询筛选器的帮助程序方法。 TableQuery.from 方法返回的引用调用 where,以对查询应用筛选器。 当通过调用 CloudTable 对象上的 execute 来执行查询时,该查询将返回指定了 CustomerEntity 结果类型的 Iterator然后,可以利用在“ForEach”循环中返回的 Iterator 来使用结果。 此代码会将查询结果中每个实体的字段打印到控制台。

try
{
    // Define constants for filters.
    final String PARTITION_KEY = "PartitionKey";
    final String ROW_KEY = "RowKey";
    final String TIMESTAMP = "Timestamp";
    // Retrieve storage account from connection-string.
    CloudStorageAccount storageAccount =
        CloudStorageAccount.parse(storageConnectionString);
    // Create the table client.
    CloudTableClient tableClient = storageAccount.createCloudTableClient();
    // Create a cloud table object for the table.
    CloudTable cloudTable = tableClient.getTableReference("people");
    // Create a filter condition where the partition key is "Smith".
    String partitionFilter = TableQuery.generateFilterCondition(
        PARTITION_KEY,
        QueryComparisons.EQUAL,
        "Smith");
    // Specify a partition query, using "Smith" as the partition key filter.
    TableQuery<CustomerEntity> partitionQuery =
        TableQuery.from(CustomerEntity.class)
        .where(partitionFilter);
    // Loop through the results, displaying information about the entity.
    for (CustomerEntity entity : cloudTable.execute(partitionQuery)) {
        System.out.println(entity.getPartitionKey() +
            " " + entity.getRowKey() +
            "\t" + entity.getEmail() +
            "\t" + entity.getPhoneNumber());
    }
}
catch (Exception e)
{
    // Output the stack trace.
    e.printStackTrace();
}

 

参考资料

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的方法

 

附录二:使用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());
相关文章
|
3月前
|
存储 监控 算法
taosd 写入与查询场景下压缩解压及加密解密的 CPU 占用分析
在当今大数据时代,时序数据库的应用越来越广泛,尤其是在物联网、工业监控、金融分析等领域。TDengine 作为一款高性能的时序数据库,凭借独特的存储架构和高效的压缩算法,在存储和查询效率上表现出色。然而,随着数据规模的不断增长,在保证数据安全性和存储效率的同时,如何优化 CPU 的资源占用,成为了一个值得深入讨论的问题。
68 1
|
3月前
|
监控 测试技术 数据库
详解Hyper-V虚拟机CPU分配方法
在Hyper-V环境中,合理分配虚拟机的CPU资源至关重要。vCPU是物理CPU的虚拟化表示,管理员可通过指定处理器数量、核心数、设置兼容性和亲和性、启用动态分配等方法优化性能。使用性能监视工具监控并调整CPU资源,避免过度分配,确保虚拟机稳定运行。定期评估和优化资源分配策略,以适应业务变化,保持最佳性能。
|
4月前
|
安全 Linux 开发工具
【Azure 环境】Azure 虚拟机上部署 DeepSeek R1 模型教程(1.5B参数)【失败】
遇见错误一:operator torchvision::nms does not exist 遇见错误二:RuntimeError: Failed to infer device type
362 22
|
5月前
|
Java Windows
【Azure Function】部署Java Function失败:报错deploy [ERROR] Status code 401和警告 'China North 3' may not be a valid region
1:deploy [ERROR] Status code 401, (empty body). 2: China North 3 may not be a valid region,please refer to https://aka.ms/maven_function_configuration#supported-regions for values. 3:  <azure.functions.maven.plugin.version>1.36.0</azure.functions.maven.plugin.version>
77 11
|
6月前
|
存储 监控 算法
深入探索Java虚拟机(JVM)的内存管理机制
本文旨在为读者提供对Java虚拟机(JVM)内存管理机制的深入理解。通过详细解析JVM的内存结构、垃圾回收算法以及性能优化策略,本文不仅揭示了Java程序高效运行背后的原理,还为开发者提供了优化应用程序性能的实用技巧。不同于常规摘要仅概述文章大意,本文摘要将简要介绍JVM内存管理的关键点,为读者提供一个清晰的学习路线图。
|
7月前
|
Java Maven Android开发
【Azure Developer】VS Code打包Java maven Project 遇见 BUILD FAILURE
Unknown lifecycle phase "lean". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>
125 5
|
7月前
|
存储 关系型数据库 MySQL
查询服务器CPU、内存、磁盘、网络IO、队列、数据库占用空间等等信息
查询服务器CPU、内存、磁盘、网络IO、队列、数据库占用空间等等信息
2683 2
|
8月前
|
存储 算法 Java
Java虚拟机(JVM)的内存管理与性能优化
本文深入探讨了Java虚拟机(JVM)的内存管理机制,包括堆、栈、方法区等关键区域的功能与作用。通过分析垃圾回收算法和调优策略,旨在帮助开发者理解如何有效提升Java应用的性能。文章采用通俗易懂的语言,结合具体实例,使读者能够轻松掌握复杂的内存管理概念,并应用于实际开发中。
|
8月前
|
存储 缓存 索引
从底层数据结构和CPU缓存两方面剖析LinkedList的查询效率为什么比ArrayList低
本文详细对比了ArrayList和LinkedList的查询效率,从底层数据结构和CPU缓存两个方面进行分析。ArrayList基于动态数组,支持随机访问,查询时间复杂度为O(1),且CPU缓存对其友好;而LinkedList基于双向链表,需要逐个节点遍历,查询时间复杂度为O(n),且CPU缓存对其帮助不大。文章还探讨了CPU缓存对数组增删操作的影响,指出缓存主要作用于读取而非修改。通过这些分析,加深了对这两种数据结构的理解。
138 2
|
9月前
|
存储 关系型数据库 MySQL
查询服务器CPU、内存、磁盘、网络IO、队列、数据库占用空间等等信息
查询服务器CPU、内存、磁盘、网络IO、队列、数据库占用空间等等信息
496 5