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

简介: 【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());
相关文章
|
12月前
|
Java 开发工具
【Azure Storage Account】Java Code访问Storage Account File Share的上传和下载代码示例
本文介绍如何使用Java通过azure-storage-file-share SDK实现Azure文件共享的上传下载。包含依赖引入、客户端创建及完整示例代码,助你快速集成Azure File Share功能。
764 6
|
Java API 开发工具
【Azure Developer】Java代码实现获取Azure 资源的指标数据却报错 "invalid time interval input"
在使用 Java 调用虚拟机 API 获取指标数据时,因本地时区设置非 UTC,导致时间格式解析错误。解决方法是在代码中手动指定时区为 UTC,使用 `ZoneOffset.ofHours(0)` 并结合 `withOffsetSameInstant` 方法进行时区转换,从而避免因时区差异引发的时间格式问题。
494 4
|
安全 Oracle Java
JAVA高级开发必备·卓伊凡详细JDK、JRE、JVM与Java生态深度解析-形象比喻系统理解-优雅草卓伊凡
JAVA高级开发必备·卓伊凡详细JDK、JRE、JVM与Java生态深度解析-形象比喻系统理解-优雅草卓伊凡
832 0
JAVA高级开发必备·卓伊凡详细JDK、JRE、JVM与Java生态深度解析-形象比喻系统理解-优雅草卓伊凡
|
安全 Java 微服务
Java 最新技术和框架实操:涵盖 JDK 21 新特性与 Spring Security 6.x 安全框架搭建
本文系统整理了Java最新技术与主流框架实操内容,涵盖Java 17+新特性(如模式匹配、文本块、记录类)、Spring Boot 3微服务开发、响应式编程(WebFlux)、容器化部署(Docker+K8s)、测试与CI/CD实践,附完整代码示例和学习资源推荐,助你构建现代Java全栈开发能力。
1175 1
|
Java Shell Maven
【Azure Container App】构建Java应用镜像时候遇无法编译错误:ERROR [build 10/10] RUN ./mvnw.cmd dependency:go-offline -B -Dproduction package
在部署Java应用到Azure Container App时,构建镜像过程中出现错误:“./mvnw.cmd: No such file or directory”。尽管项目根目录包含mvnw和mvnw.cmd文件,但依然报错。问题出现在Dockerfile构建阶段执行`./mvnw dependency:go-offline`命令时,系统提示找不到可执行文件。经过排查,确认是mvnw文件内容异常所致。最终通过重新生成mvnw文件解决该问题,镜像成功构建。
799 1
|
安全 Java API
Java最新技术(JDK 11+) 及以上 Java 最新技术之集合框架实操应用详解
本示例基于Java最新技术(JDK 11+),涵盖集合框架的核心功能,结合Java 8+特性(如Stream API、Lambda表达式)与并发编程最佳实践。内容包括:List操作(初始化、Lambda过滤、Stream处理)、Map操作(流式过滤、ConcurrentHashMap原子操作、并行流)、Set操作(TreeSet排序、CopyOnWriteArraySet并发安全)、Queue/Deque操作(优先队列、双端队列)以及高级聚合操作(集合转换、分组统计、平均值计算)。 [代码下载](https://pan.quark.cn/s/14fcf913bae6)
311 4
|
Oracle Java 关系型数据库
新手必看:Java 开发环境搭建之 JDK 与 Maven
本文分享了 Java 学习中 JDK 安装配置与 Maven 使用的入门知识,涵盖 JDK 下载安装、环境变量设置、Maven 安装配置及本地仓库与镜像设置,帮助新手快速搭建 Java 开发环境。
1904 0
|
安全 Linux 开发工具
【Azure 环境】Azure 虚拟机上部署 DeepSeek R1 模型教程(1.5B参数)【失败】
遇见错误一:operator torchvision::nms does not exist 遇见错误二:RuntimeError: Failed to infer device type
1460 22
|
算法 Java 编译器
深入理解 Java JDK —— 让我们从基础到进阶
JDK(Java Development Kit)是 Java 开发的核心工具包,包含编译、运行和调试 Java 程序所需的所有工具和库。它主要由 JVM(Java 虚拟机)、JRE(Java 运行时环境)和 Java 核心类库组成。JVM 是跨平台运行的基础,负责字节码的加载、执行和内存管理;JRE 提供运行 Java 应用的环境;核心类库则提供了丰富的 API 支持。通过编写、编译和运行一个简单的 Java 程序,可以深入理解 JDK 的工作原理。此外,JDK 还提供了 JIT 编译、垃圾回收优化和并发工具包等高级功能,帮助开发者提高程序性能和稳定性。
2161 10