如何将 Micrometer 与 Azure Application Insights Java SDK 配合使用(不建议)How to use Micrometer with Azure Application Insights Java SDK (not recommended)
重要
不再建议使用本文档中所述的方法。The approach described in this document is no longer recommended.
监视 Java 应用程序的建议方法是在不更改代码的情况下使用自动检测。The recommended approach to monitor Java applications is to use the auto-instrumentation without changing the code. Micrometer 遥测是通过 Application Insights Java 3.0 代理自动收集的,请遵循 Application Insights Java 3.0 代理的准则。Micrometer telemetry is auto-collected with the Application Insights Java 3.0 agent - follow the guidelines for Application Insights Java 3.0 agent.
备注
Application Insights Java SDK 不支持 Spring Webflux,请改用 Application Insights Java 3.0 代理。Application Insights Java SDK does not support Spring Webflux - use Application Insights Java 3.0 agent instead.
无需检测的 Application Insights Java 3.0 代理支持 Webflux 和 Micrometer。Both Webflux and Micrometer are supported in Application Insights Java 3.0 agent that requires no instrumentation.
Micrometer 应用程序监视功能可以度量基于 JVM 的应用程序代码的指标,并可用于将数据导出到偏爱的监视系统。Micrometer application monitoring measures metrics for JVM-based application code and lets you export the data to your favorite monitoring systems. 本文介绍如何对 Spring Boot 和非 Spring Boot 应用程序配合使用 Micrometer 与 Application Insights。This article will teach you how to use Micrometer with Application Insights for both Spring Boot and non-Spring Boot applications.
使用 Spring Boot 1.5xUsing Spring Boot 1.5x
将以下依赖项添加到 pom.xml 或 build.gradle 文件:Add the following dependencies to your pom.xml or build.gradle file:
- Application Insights spring-boot-starter 2.5.0 或更高版本Application Insights spring-boot-starter 2.5.0 or later
- Micrometer Azure Registry 1.1.0 或更高版本Micrometer Azure Registry 1.1.0 or above
- Micrometer Spring Legacy 1.1.0 或更高版本(用于向后移植 Spring 框架中的自动配置代码)。Micrometer Spring Legacy 1.1.0 or above (this backports the autoconfig code in the Spring framework).
- ApplicationInsights 资源ApplicationInsights Resource
步骤Steps
更新 Spring Boot 应用程序的 pom.xml 文件,在其中添加以下依赖项:Update the pom.xml file of your Spring Boot application and add the following dependencies in it:
<dependency> <groupId>com.microsoft.azure</groupId> <artifactId>applicationinsights-spring-boot-starter</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-spring-legacy</artifactId> <version>1.1.0</version> </dependency> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-azure-monitor</artifactId> <version>1.1.0</version> </dependency>
使用以下属性更新 application.properties 或 yml 文件中的 Application Insights 检测密钥:Update the application.properties or yml file with the Application Insights Instrumentation key using the following property:
azure.application-insights.instrumentation-key=<your-instrumentation-key-here>
生成并运行应用程序Build your application and run
上述代码应会使用自动收集到 Azure Monitor 的预先聚合指标启动并运行应用程序。The above should get you up and running with pre-aggregated metrics auto collected to Azure Monitor. 有关如何微调 Application Insights Spring Boot Starter 的详细信息,请参阅 GitHub 上的自述文件。For details on how to fine-tune Application Insights Spring Boot starter refer to the readme on GitHub.
使用 Spring 2.xUsing Spring 2.x
将以下依赖项添加到 pom.xml 或 build.gradle 文件:Add the following dependencies to your pom.xml or build.gradle file:
- Application Insights Spring-boot-starter 2.1.2 或更高版本Application Insights Spring-boot-starter 2.1.2 or above
- Azure-spring-boot-metrics-starters 2.0.7 或更高版本Azure-spring-boot-metrics-starters 2.0.7 or later
- Application Insights 资源Application Insights Resource
步骤:Steps:
更新 Spring Boot 应用程序的 pom.xml 文件,在其中添加以下依赖项:Update the pom.xml file of your Spring Boot application and add the following dependency in it:
<dependency> <groupId>com.microsoft.azure</groupId> <artifactId>azure-spring-boot-metrics-starter</artifactId> <version>2.0.7</version> </dependency>
使用以下属性更新 application.properties 或 yml 文件中的 Application Insights 检测密钥:Update the application.properties or yml file with the Application Insights Instrumentation key using the following property:
azure.application-insights.instrumentation-key=<your-instrumentation-key-here>
生成并运行应用程序Build your application and run
上述代码应会使用自动收集到 Azure Monitor 的预先聚合指标运行应用程序。The above should get you running with pre-aggregated metrics auto collected to Azure Monitor. 有关如何微调 Application Insights Spring Boot Starter 的详细信息,请参阅 GitHub 上的自述文件。For details on how to fine-tune Application Insights Spring Boot starter refer to the readme on GitHub.
默认指标:Default Metrics:
- 为 Tomcat、JVM 自动配置的指标、Logback 指标、Log4J 指标、运行时间指标、处理器指标、FileDescriptorMetrics。Automatically configured metrics for Tomcat, JVM, Logback Metrics, Log4J metrics, Uptime Metrics, Processor Metrics, FileDescriptorMetrics.
- 例如,如果类路径上存在 Netflix Hystrix,则我们也会获取这些指标。For example, if Netflix Hystrix is present on class path we get those metrics as well.
- 可通过添加相应的 bean 来获取以下指标。The following metrics can be available by adding respective beans.
- CacheMetrics (CaffeineCache, EhCache2, GuavaCache, HazelcastCache, JCache)CacheMetrics (CaffeineCache, EhCache2, GuavaCache, HazelcastCache, JCache)
- DataBaseTableMetricsDataBaseTableMetrics
- HibernateMetricsHibernateMetrics
- JettyMetricsJettyMetrics
- OkHttp3 指标OkHttp3 metrics
- Kafka 指标Kafka Metrics
如何禁用自动指标收集:How to turn off automatic metrics collection:
- JVM 指标:JVM Metrics:
- management.metrics.binders.jvm.enabled=falsemanagement.metrics.binders.jvm.enabled=false
- Logback 指标:Logback Metrics:
- management.metrics.binders.logback.enabled=falsemanagement.metrics.binders.logback.enabled=false
- 运行时间指标:Uptime Metrics:
- management.metrics.binders.uptime.enabled=falsemanagement.metrics.binders.uptime.enabled=false
- 处理器指标:Processor Metrics:
- management.metrics.binders.processor.enabled=falsemanagement.metrics.binders.processor.enabled=false
- FileDescriptorMetrics:FileDescriptorMetrics:
- management.metrics.binders.files.enabled=falsemanagement.metrics.binders.files.enabled=false
- Hystrix 指标(如果类路径中包含该库):Hystrix Metrics if library on classpath:
- management.metrics.binders.hystrix.enabled=falsemanagement.metrics.binders.hystrix.enabled=false
- AspectJ 指标(如果类路径中包含该库):AspectJ Metrics if library on classpath:
- spring.aop.enabled=falsespring.aop.enabled=false
备注
在 Spring Boot 应用程序的 application.properties 或 application.yml 文件中指定上述属性Specify the properties above in the application.properties or application.yml file of your Spring Boot application
对非 Spring Boot Web 应用程序使用 MicrometerUse Micrometer with non-Spring Boot web applications
将以下依赖项添加到 pom.xml 或 build.gradle 文件:Add the following dependencies to your pom.xml or build.gradle file:
- Application Insights Web Auto 2.5.0 或更高版本Application Insights Web Auto 2.5.0 or later
- Micrometer Azure Registry 1.1.0 或更高版本Micrometer Azure Registry 1.1.0 or above
- Application Insights 资源Application Insights Resource
步骤:Steps:
将以下依赖项添加到 pom.xml 或 build.gradle 文件中:Add the following dependencies in your pom.xml or build.gradle file:
<dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-azure-monitor</artifactId> <version>1.1.0</version> </dependency> <dependency> <groupId>com.microsoft.azure</groupId> <artifactId>applicationinsights-web-auto</artifactId> <version>2.5.0</version> </dependency>
将
ApplicationInsights.xml
文件放入 resources 文件夹中:PutApplicationInsights.xml
file in the resources folder:<?xml version="1.0" encoding="utf-8"?> <ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings" schemaVersion="2014-05-30"> <!-- The key from the portal: --> <InstrumentationKey>** Your instrumentation key **</InstrumentationKey> <!-- HTTP request component (not required for bare API) --> <TelemetryModules> <Add type="com.microsoft.applicationinsights.web.extensibility.modules.WebRequestTrackingTelemetryModule"/> <Add type="com.microsoft.applicationinsights.web.extensibility.modules.WebSessionTrackingTelemetryModule"/> <Add type="com.microsoft.applicationinsights.web.extensibility.modules.WebUserTrackingTelemetryModule"/> </TelemetryModules> <!-- Events correlation (not required for bare API) --> <!-- These initializers add context data to each event --> <TelemetryInitializers> <Add type="com.microsoft.applicationinsights.web.extensibility.initializers.WebOperationIdTelemetryInitializer"/> <Add type="com.microsoft.applicationinsights.web.extensibility.initializers.WebOperationNameTelemetryInitializer"/> <Add type="com.microsoft.applicationinsights.web.extensibility.initializers.WebSessionTelemetryInitializer"/> <Add type="com.microsoft.applicationinsights.web.extensibility.initializers.WebUserTelemetryInitializer"/> <Add type="com.microsoft.applicationinsights.web.extensibility.initializers.WebUserAgentTelemetryInitializer"/> </TelemetryInitializers> </ApplicationInsights>
示例 Servlet 类(发出计时器指标):Sample Servlet class (emits a timer metric):
@WebServlet("/hello") public class TimedDemo extends HttpServlet { private static final long serialVersionUID = -4751096228274971485L; @Override @Timed(value = "hello.world") protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("Hello World!"); MeterRegistry registry = (MeterRegistry) getServletContext().getAttribute("AzureMonitorMeterRegistry"); //create new Timer metric Timer sampleTimer = registry.timer("timer"); Stream<Integer> infiniteStream = Stream.iterate(0, i -> i+1); infiniteStream.limit(10).forEach(integer -> { try { Thread.sleep(1000); sampleTimer.record(integer, TimeUnit.MILLISECONDS); } catch (Exception e) {} }); } @Override public void init() throws ServletException { System.out.println("Servlet " + this.getServletName() + " has started"); } @Override public void destroy() { System.out.println("Servlet " + this.getServletName() + " has stopped"); } }
示例配置类:Sample configuration class:
@WebListener public class MeterRegistryConfiguration implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { // Create AzureMonitorMeterRegistry private final AzureMonitorConfig config = new AzureMonitorConfig() { @Override public String get(String key) { return null; } @Override public Duration step() { return Duration.ofSeconds(60);} @Override public boolean enabled() { return false; } }; MeterRegistry azureMeterRegistry = AzureMonitorMeterRegistry.builder(config); //set the config to be used elsewhere servletContextEvent.getServletContext().setAttribute("AzureMonitorMeterRegistry", azureMeterRegistry); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { } }
若要详细了解指标,请参阅 Micrometer 文档。To learn more about metrics, refer to the Micrometer documentation.
有关演示如何创建不同类型的指标的其他示例代码,请参阅官方的 Micrometer GitHub 存储库。Other sample code on how to create different types of metrics can be found inthe official Micrometer GitHub repo.
如何绑定其他指标集合How to bind additional metrics collection
SpringBoot/SpringSpringBoot/Spring
创建相应指标类别的 bean。Create a bean of the respective metric category. 例如,假设我们需要 Guava 缓存指标:For example, say we need Guava cache Metrics:
@Bean
GuavaCacheMetrics guavaCacheMetrics() {
Return new GuavaCacheMetrics();
}
有多个指标默认未启用,但可按上述方式绑定。There are several metrics that are not enabled by default but can be bound in the above fashion. 有关完整列表,请参阅官方的 Micrometer GitHub 存储库。For a complete list, refer to the official Micrometer GitHub repo.
非 Spring 应用Non-Spring apps
将以下绑定代码添加到配置文件:Add the following binding code to the configuration file:
New GuavaCacheMetrics().bind(registry);
后续步骤Next steps
- 若要详细了解 Micrometer,请参阅官方的 Micrometer 文档。To learn more about Micrometer, see the official Micrometer documentation.
- 若要了解 Azure 上的 Spring,请参阅官方的 Azure 上的 Spring 文档。To learn about Spring on Azure, see the official Spring on Azure documentation.