【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 resourceUripath True
- string
资源的标识符。
api-versionquery True
- string
客户端 Api 版本。
$filterquery
- string
$filter用于减少返回的指标数据集。
示例:
指标包含元数据 A、B 和 C。
- 返回所有时间序列 C,其中 A = a1 和 B = b1 或 b2
$filter_eq 'a1' 和 B eq 'b1' 或 B eq 'b2' 和 C eq '#'
- 无效变体:
$filter=eq 'a1'和 B eq 'b1' 和 C eq '*' 或 B = 'b2'
这是无效的,因为逻辑或运算符不能分隔两个不同的元数据名称。
- 返回所有时间序列,其中 A = a1,B = b1 和 C = c1:
$filter=eq 'a1'和 B eq 'b1' 和 C eq 'c1'
- 返回所有时间序列,其中 A = a1
$filter_aq 'a1' 和 B eq '和 C eq''. aggregationquery
- string
要检索的聚合类型(逗号分隔)的列表。
intervalquery
- string
duration
查询的间隔(即时粒)。
metricnamesquery
- string
要检索的指标(逗号分隔)的名称。
metricnamespacequery
- string
用于查询指标定义的指标命名空间。
orderbyquery
- string
用于对结果进行排序的聚合和排序方向。 只能指定一个订单。 示例:总和 asc。
resultTypequery 减少收集的数据集。 允许的语法取决于操作。 有关详细信息,请参阅操作说明。
timespanquery
- string
查询的时间跨度。 它是具有以下格式"startDateTime_ISO/endDateTime_ISO"的字符串。
topquery
- 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());
【Azure Developer】通过Azure提供的Azue Java JDK 查询虚拟机的CPU使用率和内存使用率的更多相关文章
- 【Azure Developer】Azure Graph SDK获取用户列表的问题: SDK中GraphServiceClient如何指向中国区的Endpoint:https://microsoftgraph.chinacloudapi.cn/v1.0
问题描述 想通过Java SDK的方式来获取Azure 门户中所列举的用户.一直报错无法正常调用接口,错误信息与AAD登录认证相关,提示tenant not found. 想要实现的目的,通过代码方式 ...
- 【Azure Developer】记录一次使用Java Azure Key Vault Secret示例代码生成的Jar包,单独运行出现 no main manifest attribute, in target/demo-1.0-SNAPSHOT.jar 错误消息
问题描述 创建一个Java Console程序,用于使用Azure Key Vault Secret.在VS Code中能正常Debug,但是通过mvn clean package打包为jar文件后, ...
- 【Azure Developer】Azure Automation 自动化账号生成的时候怎么生成连接 与证书 (Connection & Certificate)
Azure Automation :The Azure Automation service provides a highly reliable and scalable workflow exec ...
- 【Azure Developer】Azure Logic App 示例: 解析 Request Body 的 JSON 的表达式? triggerBody()?
问题描述 通过Azure Logic App(逻辑应用)实现无代码的处理JSON数据.但是如何获取Request Body中的一个属性值呢? 例如:如何来获取以下JSON结构中的 ObjectName ...
- Java对象在虚拟机中的创建、内存分布、访问定位以及死亡判定
转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6535156.html 一:虚拟机中对象的创建 1:虚拟机遇到new指令时,在常量池检索是否有对应的符号引用, ...
- Windows Azure HandBook (2) Azure China提供的服务
<Windows Azure Platform 系列文章目录> 对于传统的自建数据中心,从底层的Network,Storage,Servers,Virtualization,中间层的OS, ...
- 获取指定订阅下所有Azure ARM虚拟机配置(CPU核数,内存大小,磁盘信息)的使用情况
脚本内容: <# .SYNOPSIS This script grab all ARM VM VHD file in the subscription and caculate VHD size ...
- Linux下使用java获取cpu、内存使用率
原文地址:http://www.voidcn.com/article/p-yehrvmep-uo.html 思路如下:Linux系统中可以用top命令查看进程使用CPU和内存情况,通过Runtime类 ...
- 【Azure Developer】使用Java代码启动Azure VM(虚拟机)
问题描述 在使用Java的启动Azure VM的过程中,遇见了com.azure.core.management.exception.ManagementException: Status code ...
随机推荐
- 【转】CentOS7 64位安装mysql教程
从最新版本的linux系统开始,默认的是 Mariadb而不是mysql!这里依旧以mysql为例进行展示 1.先检查系统是否装有mysql rpm -qa | grep mysql 这里返回空值,说 ...
- arm-linux 修改rootfs登录名和密码
1.保证文件系统busybox中已经配置了login登录功能. 2.修改命令行前缀名 (1)进到/etc/sysconfig,找到HOSTNAME文件,修改里面为想要的登录名后,之后再重新加载文件系统 ...
- iOS Transform坐标变化
在使用CGContext时,由于Quartz 2D与UIKit坐标不一致,所以需要对context进行再一次的变化,达到预期的效果. 1. 不同坐标原点介绍 在Quartz 2D中,坐标原点在画布的左 ...
- webug第十关:文件下载
第十关:文件下载 点击下载 将fname改为download.php....不过好像它的配置有点问题
- 使用phpExcel读取excel文件
include_once '../include/common.inc.php'; include_once MC_ROOT.'include/smarty.inc.php'; date_defaul ...
- pandas 生成html文档,支持可添加多个表
如何通过pandas生成html格式?如何通过pandas生成html文件文件中包含多个表单Balance_64_data = pd.read_sql(Balance_64_sql,engine)df ...
- 为什么Java不允许创建范型数组
问题示例 List<Integer>[] intListArr = new ArrayList<Integer>[8]; // 编译时报错 能看到这么看似没啥问题的一个简单语句 ...
- phpstorm里面添加swoole代码提示
https://yq.aliyun.com/articles/44246 下载代码: git clone https://github.com/eaglewu/swoole-ide-helper.gi ...
- 抓包工具fiddler使用-初级
参考 https://kb.cnblogs.com/page/130367/#introduce
- 3. git命令行操作之远程库操作
3.1 基本操作 注册GitHub账号 在本地创建一个本地库并初始化 登录到gitHub创建一个远程库 注意:windows的凭据管理器中会保存github登录信息.如果要切换登录者,先删除相应凭据 ...