【Azure Developer】Java代码实现获取Azure 资源的指标数据却报错 "invalid time interval input"

简介: 在使用 Java 调用虚拟机 API 获取指标数据时,因本地时区设置非 UTC,导致时间格式解析错误。解决方法是在代码中手动指定时区为 UTC,使用 `ZoneOffset.ofHours(0)` 并结合 `withOffsetSameInstant` 方法进行时区转换,从而避免因时区差异引发的时间格式问题。

问题描述

在使用 Java 代码调用虚拟机(VM)API获取指标数据时,出现时间格式解析错误。

错误信息:

'{

"code": "BadRequest",

"message": "Detected invalid time interval input: 2024-03-13T13:33:05.123 15:00/2024-03-13T13:48:05.233 15:00, supported Iso 8601 time interval format: (Datetime/Datetime, Datetime/Duration, Duration/Datetime, Duration)"

}'

JAVA 代码:

static void query() 
 {
     MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder()
        .endpoint("https://management.chinacloudapi.cn")
        .credential(new DefaultAzureCredentialBuilder().build())
        .buildClient();

    String resourceId = "<resource id>";
    Response<MetricsQueryResult> metricsResponse = metricsQueryClient
        .queryResourceWithResponse(resourceId, 
                                    Arrays.asList("CpuTime", "Requests"),
                                    new MetricsQueryOptions()
                                        .setGranularity(Duration.ofHours(1))
                                        .setTimeInterval(new QueryTimeInterval(OffsetDateTime.now().minusDays(1), OffsetDateTime.now()))
                                        .setAggregations(Arrays.asList(AggregationType.AVERAGE, AggregationType.COUNT)),
                                    Context.NONE);

    MetricsQueryResult metricsQueryResult = metricsResponse.getValue();

    for (MetricResult metric : metricsQueryResult.getMetrics()) 
    {
        System.out.println("Metric name " + metric.getMetricName());
        for (TimeSeriesElement timeSeriesElement : metric.getTimeSeries()) 
        {
            System.out.println("Dimensions " + timeSeriesElement.getMetadata());
            for (MetricValue metricValue : timeSeriesElement.getValues()) 
            {
                System.out.println(metricValue.getTimeStamp() + " " + metricValue.getTotal());
            }
        }
    }
}


这个会是什么原因导致的呢?

 

问题解答

添加日志,对比代码生成的时间格式字符串后,发现问题根源于本地执行环境的时区设置相关!

因为 Java SDK中timespan参数仅支持UTC的ZoneOffset。如果本地环境设置为非UTC的时区,例如:export TZ="/usr/share/zoneinfo/Hongkong" 就可以复现此问题。

鉴于此种情况,如果不修改本地电脑环境的情况下,可以在代码中进行指定时间为UTC时区。

添加代码:ZoneOffset zoneOffsetUTC = ZoneOffset.ofHours(0);, 然后在设置 setTimeInterval 中指定时区  OffsetDateTime.now().withOffsetSameInstant(zoneOffsetUTC)。这样就可以解决时间格式因时区不同而产生的问题!


修改后的代码为:

static void query() 
 {
     MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder()
        .endpoint("https://management.chinacloudapi.cn")
        .credential(new DefaultAzureCredentialBuilder().build())
        .buildClient();
    String resourceId = "<resource id>";
    
    ZoneOffset zoneOffsetUTC = ZoneOffset.ofHours(0);
   
    Response<MetricsQueryResult> metricsResponse = metricsQueryClient
        .queryResourceWithResponse(resourceId, 
                                    Arrays.asList("CpuTime", "Requests"),
                                    new MetricsQueryOptions()
                                        .setGranularity(Duration.ofHours(1))
                                        .setTimeInterval(new QueryTimeInterval(OffsetDateTime.now().minusDays(1).withOffsetSameInstant(zoneOffsetUTC), OffsetDateTime.now().withOffsetSameInstant(zoneOffsetUTC)))
                                        .setAggregations(Arrays.asList(AggregationType.AVERAGE, AggregationType.COUNT)),
                                    Context.NONE);
    MetricsQueryResult metricsQueryResult = metricsResponse.getValue();
    for (MetricResult metric : metricsQueryResult.getMetrics()) 
    {
        System.out.println("Metric name " + metric.getMetricName());
        for (TimeSeriesElement timeSeriesElement : metric.getTimeSeries()) 
        {
            System.out.println("Dimensions " + timeSeriesElement.getMetadata());
            for (MetricValue metricValue : timeSeriesElement.getValues()) 
            {
                System.out.println(metricValue.getTimeStamp() + " " + metricValue.getTotal());
            }
        }
    }
}


 

参考资料

Azure Resource Metrics - List :https://learn.microsoft.com/en-us/rest/api/monitor/metrics/list?view=rest-monitor-2023-10-01&tabs=HTTP

timespan :The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'.

 

 


 


当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!

相关文章
|
12月前
|
JSON 自然语言处理 运维
不只是告警:用阿里云可观测 MCP 实现 AK 高效安全审计
本文介绍了运维工程师小王如何通过阿里云操作审计日志与MCP结合,快速排查一次AK异常访问事件。借助自然语言查询技术,小王实现了对敏感操作、高风险行为及Root账号使用的实时追踪与分析,提升了安全响应效率与系统可控性。
594 32
|
开发者 黑灰产治理
阿里云开发者社区积分细则
阿里云开发者社区,积分规则、领取、过期等相关说明
3704 19
|
11月前
|
SQL Java 数据库连接
MyBatis 的映射关系
MyBatis 核心功能之一是映射关系,支持一对一、一对多和多对多三种 ORM 映射。通过实体类与配置文件结合,开发者可灵活实现数据关联,提升数据库操作效率。
510 4
|
11月前
|
XML Java 数据库连接
MyBatis的常见配置
MyBatis 常见配置包括数据库连接、类型别名、映射器等核心模块,合理配置可提升开发效率与系统性能。主要内容涵盖核心配置文件结构、关键配置项详解及配置优先级说明。
849 4
|
12月前
|
JSON 自然语言处理 搜索推荐
银行卡归属地及开户行查询API查询实战指南
银行卡归属地及开户行查询API,通过卡号快速识别发卡行、开户地及卡种信息,支持全国1500+银行,数据实时更新。提供结构化数据返回,广泛应用于支付、风控、用户画像等场景,助力金融系统高效、安全运行。
3774 9
人工智能 安全 IDE
999 30
|
11月前
|
Prometheus 监控 Kubernetes
《云原生场景下Prometheus指标采集异常的深度排查与架构修复》
本文聚焦云原生监控系统中Prometheus采集K8s容器指标的“间歇性无数据”问题,还原其技术环境(K8s 1.28.3、Prometheus 2.45.0等)与故障现象(指标缺失5-15分钟,高峰期频发)。排查发现,根源在于kubelet的cadvisor指标生成线程不足、缓存策略不当,叠加Calico iptables转发延迟。通过优化kubelet参数(增线程、缩缓存)、调整Prometheus采集策略(延间隔、分片采集)、切换Calico为IPVS模式,问题得以解决。同时给出长期监控预警方案,为云原生监控运维提供实践思路,强调全链路协同优化的重要性。
400 4
|
11月前
|
传感器 机器学习/深度学习 算法
无人机视觉定位研究(Matlab代码实现)
无人机视觉定位研究(Matlab代码实现)
282 0
|
11月前
|
传感器 机器学习/深度学习 编解码
使用显著性检测的可见光和红外图像的两尺度图像融合(Matlab代码实现)
使用显著性检测的可见光和红外图像的两尺度图像融合(Matlab代码实现)
314 3