【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 ...
随机推荐
- ceph的pg平衡插件balancer
前言 ceph比较老的版本使用的reweight或者osd weight来调整平衡的,本篇介绍的是ceph新的自带的插件balancer的使用,官网有比较详细的操作手册可以查询 使用方法 查询插件的开 ...
- 编译一个支持多线程的php安装包
前言 因为项目上的需要,需要用到php,一般来说,用默认的版本和配置就可以满足大多数的场景,因为需要加入多线程,所以需要自己编译一个包 一般来说,发行的包的版本的配置选项和代码都是最稳定的,所以在大多 ...
- ASP.NET Core管道详解[2]: HttpContext本质论
ASP.NET Core请求处理管道由一个服务器和一组有序排列的中间件构成,所有中间件针对请求的处理都在通过HttpContext对象表示的上下文中进行.由于应用程序总是利用服务器来完成对请求的接收和 ...
- html2image
测试没有,生产有 也就是写死的显示,配置的不显示
- YARN-MapReduce的作业提交流程
YARN分布式资源管理系统 组成: ResourceManager:YARN的资源管理器,主节点,通过NodeManager管理集群中所有的资源 NodeManager:YARN的节点管理器,从节点, ...
- 总结MathType中输入小于号的方法
作为一款专业的公式编辑软件,MathType可谓是非常强大,先不说其编辑公式是多么的方便.迅速,但就打开软件界面,看到不可估算的数学符号有那么多,你就会感叹它的强大,竟然能把绝大部分的数学符号都汇聚于 ...
- 将多个PDF文件整合成一个文件
pdfFactory不仅可以将单个文件创建为PDF文件进行打印,还可以将多个文件整合为一个PDF文件,同时,也可以随时删除其中的一些文件,创建新的PDF文件. 图1:pdfFactory工具界面 一. ...
- 如何用ABBYY FineReader提取图片中的文字
作为OCR文字识别软件中的佼佼者,可能大家对于ABBYY FineReader的使用还不熟练,没关系,今天小编就为大家演示,如何用ABBYY FineReader这款文字识别软件,将一张截图中的文字识 ...
- 电子邮件怎么用EasyRecovery恢复,只需简单5步
在日常工作中,我们常常会用电子邮件与上事.客户等协商工作事务.电子邮件快捷.方便,慢慢地成为我们工作中不可缺少的沟通工具之一. 然而使用的过程中,你会发现垃圾邮件也越积越多了,平时,我看到积压的垃圾邮 ...
- Java数据结构(七)—— 排序算法
排序算法(Sort Algorithm) 排序算法介绍和分类 将一组数据,依指定顺序进行排列 排序的分类 内部排序 指将需要处理的所有数据都加载到内部存储器中进行排序 外部排序 数据量过大,无法全部加 ...