【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 ...
随机推荐
- 2种方式(线程间通信/互斥锁)实现两个线程,一个线程打印1-52,另一个线程打印字母A-Z,打印顺序为12A34B56C......5152Z
//2019/06/13 本周HT面试遇到的问题,答得不是很好,自己重新做一下.面试只需要写出线程间通信的方式,//我当时大致知道思路,因为之前看过马士兵老师的多线程视频,但是代码写出来估计编译都是报 ...
- 练习启动各种浏览器的同时加载插件:Firefox, Chrome, IE
# -*- coding:utf-8 -*-import osimport seleniumfrom selenium import webdriverfrom selenium.webdriver. ...
- C语言复习系列-转义字符
C语言复习系列-转义字符 准备学习stm32单片机,感觉需要复习一下C语言,翻看了菜鸟教程,竟然有不少地方看不懂,真让人汗颜······ 转义字符大部分语言里面都有,至少我学过的里面都有,在这些语言中 ...
- Java 合并多个文件内容到一个文件(递归遍历某个文件夹下所有文件)
这段代码通过Java I/O流API实现将多个文件合并到一个文件中,输出为文本文件,提供一个支持语法高亮的网站,http://www.codeinword.com/ 适合粘贴代码到word文档,小巧实 ...
- 通过一道CTF学习HTTP协议请求走私
HTTP请求走私 HTTP请求走私 HTTP请求走私是针对于服务端处理一个或者多个接收http请求序列的方式,进行绕过安全机制,实施未授权访问一种攻击手段,获取敏感信息,并直接危害其他用户. 请求走私 ...
- swupdate实例
平台:imx8mm 系统:linux 4.4 如果需要系统了解swupdate,请参考文章:嵌入式系统更新swupdate分类 一.制作升级包 emmcsetup.lua用来描述update执 ...
- Ubuntu16.04安装搜狗输入法报错:dkpg:处理归档sogoupinyin.deb(--install)时出错,安装sogoupinyin将破坏fcitx-ui-qimpanel
系统:ubuntu16.04 事件:安装搜狗拼音时报错 报错信息(ubuntu语言是英文的报错信息): dpkg: regarding sogoupinyin_2.3.2.07_amd64-831.d ...
- CorelDRAW多个文件如何批量导出JPG
好多同学对于CorelDRAW 2018批量导出图片格式的操作不太了解.这种情况比较常见,比如设计了一本画册,在同一个文档中页面比较多,如果一页一页导出那将是一项巨大的工程,这时候我们就会想到CDR的 ...
- 如何使用OCR编辑器检查和识别文本
ABBYY FineReader 15(Windows系统)中的OCR编辑器能帮助用户对扫描仪或者数码相机获取的图像文件进行自动文本识别,OCR区域绘制等,使这些图像文件能进一步转换为可编辑的格式.其 ...
- 解决Tuxera NTFS for Mac软件安装问题
在听到小凡的电话说"Tuxera NTFS for Mac软件安装失败,怎么办"的时候,小编心里真像有一万头草泥马在奔腾--苹果软件还能安装失败!? 挥手把一万头草泥马赶走,脑补着 ...