Spring Boot Actuator / Swagger
I'm working on Spring Boot application and i use Swagger for the documentation.
I have adding Spring Boot Actuator on my application, but now i want to add the new services creating by actuator (/health /metrics ..) on my swagger documentation.
I don't find how configure Actuator and Swagger.
You can configure in Swagger which paths you wanted added to the documentation.
@Bean public Docket appApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .... }
Will display all available endpoints.
.paths(PathSelectors.ant("/mypath/**"))
will limit only to endpoints exposed in mypath.
spring-boot-starter-actuator模块的实现对于实施微服务的中小团队来说,
可以有效地减少监控系统在采集应用指标时的开发量。
当然,它也并不是万能的,有时候我们也需要对其做一些简单的扩展来帮助我们实现自身系统个性化的监控需求。
下面,在本文中,我们将详解的介绍一些关于spring-boot-starter-actuator模块的内容,包括它的原生提供的端点以及一些常用的扩展和配置方式。
/autoconfig:该端点用来获取应用的自动化配置报告,其中包括所有自动化配置的候选项。
同时还列出了每个候选项自动化配置的各个先决条件是否满足。
所以,该端点可以帮助我们方便的找到一些自动化配置为什么没有生效的具体原因。
该报告内容将自动化配置内容分为两部分:
positiveMatches中返回的是条件匹配成功的自动化配置
negativeMatches中返回的是条件匹配不成功的自动化配置
{ "positiveMatches": { // 条件匹配成功的 "EndpointWebMvcAutoConfiguration": [ { "condition": "OnClassCondition", "message": "@ConditionalOnClass classes found:
javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet" }, { "condition": "OnWebApplicationCondition", "message": "found web application StandardServletEnvironment" } ], ... }, "negativeMatches": { // 条件不匹配成功的 "HealthIndicatorAutoConfiguration.DataSourcesHealthIndicatorConfiguration": [ { "condition": "OnClassCondition", "message": "required @ConditionalOnClass classes not found: org.springframework.jdbc.core.JdbcTemplate" } ], ... } }
从如上示例中我们可以看到,每个自动化配置候选项中都有一系列的条件,
比如上面没有成功匹配的HealthIndicatorAutoConfiguration.DataSourcesHealthIndicatorConfiguration配置,
它的先决条件就是需要在工程中包含org.springframework.jdbc.core.JdbcTemplate类,
由于我们没有引入相关的依赖,它就不会执行自动化配置内容。
所以,当我们发现有一些期望的配置没有生效时,就可以通过该端点来查看没有生效的具体原因。
/configprops:该端点用来获取应用中配置的属性信息报告。
从下面该端点返回示例的片段中,
我们看到返回了关于该短信的配置信息,
prefix属性代表了属性的配置前缀,
properties代表了各个属性的名称和值。
所以,我们可以通过该报告来看到各个属性的配置路径,
比如我们要关闭该端点,就可以通过使用endpoints.configprops.enabled=false来完成设置。
{ "configurationPropertiesReportEndpoint": { "prefix": "endpoints.configprops", "properties": { "id": "configprops", "sensitive": true, "enabled": true } }, ... }
/env:该端点与/configprops不同,它用来获取应用所有可用的环境属性报告。
包括:环境变量、JVM属性、应用的配置配置、命令行中的参数。
从下面该端点返回的示例片段中,
我们可以看到它不仅返回了应用的配置属性,还返回了系统属性、环境变量等丰富的配置信息,
其中也包括了应用还没有没有使用的配置。
所以它可以帮助我们方便地看到当前应用可以加载的配置信息,
并配合@ConfigurationProperties注解将它们引入到我们的应用程序中来进行使用。
另外,为了配置属性的安全,对于一些类似密码等敏感信息,该端点都会进行隐私保护,
但是我们需要让属性名中包含:password、secret、key这些关键词,
这样该端点在返回它们的时候会使用*来替代实际的属性值。
/mappings:该端点用来返回所有Spring MVC的控制器映射关系报告。
从下面的示例片段中,我们可以看该报告的信息与我们在启用Spring MVC的Web应用时输出的日志信息类似,
其中
bean属性标识了该映射关系的请求处理器,
method属性标识了该映射关系的具体处理类和处理函数。
{ "/webjars/**": { "bean": "resourceHandlerMapping" }, "/**": { "bean": "resourceHandlerMapping" }, "/**/favicon.ico": { "bean": "faviconHandlerMapping" }, "{[/hello]}": { "bean": "requestMappingHandlerMapping", "method": "public java.lang.String com.didispace.web.HelloController.index()" }, "{[/mappings || /mappings.json],methods=[GET],produces=[application/json]}": { "bean": "endpointHandlerMapping", "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()" }, ... }
/info:该端点用来返回一些应用自定义的信息。
默认情况下,该端点只会返回一个空的json内容。
我们可以在application.properties配置文件中通过info前缀来设置一些属性,比如下面这样:
info.app.name=spring-boot-hello
info.app.version=v1.0.0
再访问/info端点,我们可以得到下面的返回报告,其中就包含了上面我们在应用自定义的两个参数。
{ "app": { "name": "spring-boot-hello", "version": "v1.0.0" } }
度量指标类
上面我们所介绍的应用配置类端点所提供的信息报告在应用启动的时候都已经基本确定了其返回内容,
可以说是一个静态报告。而度量指标类端点提供的报告内容则是动态变化的,
这些端点提供了应用程序在运行过程中的一些快照信息,
比如:内存使用情况、HTTP请求统计、外部资源指标等。
这些端点对于我们构建微服务架构中的监控系统非常有帮助,
由于Spring Boot应用自身实现了这些端点,所以我们可以很方便地利用它们来收集我们想要的信息,
以制定出各种自动化策略。下面,我们就来分别看看这些强大的端点功能。
/metrics:该端点用来返回当前应用的各类重要度量指标,比如:内存信息、线程信息、垃圾回收信息等。
{ "mem": 541305, "mem.free": 317864, "processors": 8, "instance.uptime": 33376471, "uptime": 33385352, "systemload.average": -1, "heap.committed": 476672, "heap.init": 262144, "heap.used": 158807, "heap": 3701248, "nonheap.committed": 65856, "nonheap.init": 2496, "nonheap.used": 64633, "nonheap": 0, "threads.peak": 22, "threads.daemon": 20, "threads.totalStarted": 26, "threads": 22, "classes": 7669, "classes.loaded": 7669, "classes.unloaded": 0, "gc.ps_scavenge.count": 7, "gc.ps_scavenge.time": 118, "gc.ps_marksweep.count": 2, "gc.ps_marksweep.time": 234, "httpsessions.max": -1, "httpsessions.active": 0, "gauge.response.beans": 55, "gauge.response.env": 10, "gauge.response.hello": 5, "gauge.response.metrics": 4, "gauge.response.configprops": 153, "gauge.response.star-star": 5, "counter.status.200.beans": 1, "counter.status.200.metrics": 3, "counter.status.200.configprops": 1, "counter.status.404.star-star": 2, "counter.status.200.hello": 11, "counter.status.200.env": 1 }
从上面的示例中,我们看到有这些重要的度量值:
系统信息:包括处理器数量processors、运行时间uptime和instance.uptime、系统平均负载systemload.average。
mem.*:内存概要信息,包括分配给应用的总内存数量以及当前空闲的内存数量。这些信息来自java.lang.Runtime。
heap.*:堆内存使用情况。这些信息来自java.lang.management.MemoryMXBean接口中getHeapMemoryUsage方法获取的java.lang.management.MemoryUsage。
nonheap.*:非堆内存使用情况。这些信息来自java.lang.management.MemoryMXBean接口中getNonHeapMemoryUsage方法获取的java.lang.management.MemoryUsage。
threads.*:线程使用情况,包括线程数、守护线程数(daemon)、线程峰值(peak)等,这些数据均来自java.lang.management.ThreadMXBean。
classes.*:应用加载和卸载的类统计。这些数据均来自java.lang.management.ClassLoadingMXBean。
gc.*:垃圾收集器的详细信息,包括垃圾回收次数gc.ps_scavenge.count、垃圾回收消耗时间gc.ps_scavenge.time、标记-清除算法的次数gc.ps_marksweep.count、标记-清除算法的消耗时间gc.ps_marksweep.time。这些数据均来自java.lang.management.GarbageCollectorMXBean。
httpsessions.*:Tomcat容器的会话使用情况。包括最大会话数httpsessions.max和活跃会话数httpsessions.active。该度量指标信息仅在引入了嵌入式Tomcat作为应用容器的时候才会提供。
gauge.*:HTTP请求的性能指标之一,它主要用来反映一个绝对数值。比如上面示例中的gauge.response.hello: 5,它表示上一次hello请求的延迟时间为5毫秒。
counter.*:HTTP请求的性能指标之一,它主要作为计数器来使用,记录了增加量和减少量。
如上示例中counter.status.200.hello: 11,它代表了hello请求返回200状态的次数为11。
对于gauge.*和counter.*的统计,这里有一个特殊的内容请求star-star,它代表了对静态资源的访问。
这两类度量指标非常有用,我们不仅可以使用它默认的统计指标,还可以在程序中轻松的增加自定义统计值。
只需要通过注入org.springframework.boot.actuate.metrics.CounterService和org.springframework.boot.actuate.metrics.GaugeService来实现自定义的统计指标信息。
比如:我们可以像下面这样自定义实现对hello接口的访问次数统计。
@RestController public class HelloController { @Autowired private CounterService counterService; @RequestMapping("/hello") public String greet() { counterService.increment("didispace.hello.count"); return ""; } }
/metrics端点可以提供应用运行状态的完整度量指标报告,这项功能非常的实用,
但是对于监控系统中的各项监控功能,它们的监控内容、数据收集频率都有所不同,
如果我们每次都通过全量获取报告的方式来收集,略显粗暴。
所以,我们还可以通过/metrics/{name}接口来更细粒度的获取度量信息,
比如我们可以通过访问/metrics/mem.free来获取当前可用内存数量。
/health:该端点在一开始的示例中我们已经使用过了,它用来获取应用的各类健康指标信息。
在spring-boot-starter-actuator模块中自带实现了一些常用资源的健康指标检测器。
这些检测器都通过HealthIndicator接口实现,并且会根据依赖关系的引入实现自动化装配,
比如用于检测磁盘的DiskSpaceHealthIndicator、检测DataSource连接是否可用的DataSourceHealthIndicator等。
有时候,我们可能还会用到一些Spring Boot的Starter POMs中还没有封装的产品来进行开发,
比如:当使用RocketMQ作为消息代理时,由于没有自动化配置的检测器,
所以我们需要自己来实现一个用来采集健康信息的检测器。
比如,我们可以在Spring Boot的应用中,
为org.springframework.boot.actuate.health.HealthIndicator接口实现一个对RocketMQ的检测器类:
@Component public class RocketMQHealthIndicator implements HealthIndicator { @Override public Health health() { int errorCode = check(); if (errorCode != 0) { return Health.down().withDetail("Error Code", errorCode).build(); } return Health.up().build(); } private int check() { // 对监控对象的检测操作 } }
通过重写health()函数来实现健康检查,返回的Heath对象中,共有两项内容,一个是状态信息,
除了该示例中的UP与DOWN之外,还有UNKNOWN和OUT_OF_SERVICE,可以根据需要来实现返回;
还有一个详细信息,采用Map的方式存储,在这里通过withDetail函数,注入了一个Error Code信息,我们也可以填入一下其他信息,
比如,检测对象的IP地址、端口等。
重新启动应用,并访问/health接口,我们在返回的JSON字符串中,将会包含了如下信息:
"rocketMQ": { "status": "UP" }
/dump:该端点用来暴露程序运行中的线程信息。
它使用java.lang.management.ThreadMXBean的dumpAllThreads方法来返回所有含有同步信息的活动线程详情。
/trace:该端点用来返回基本的HTTP跟踪信息。
默认情况下,跟踪信息的存储采用org.springframework.boot.actuate.trace.InMemoryTraceRepository实现的内存方式,始终保留最近的100条请求记录。
它记录的内容格式如下:
[ { "timestamp": 1482570022463, "info": { "method": "GET", "path": "/metrics/mem", "headers": { "request": { "host": "localhost:8881", "connection": "keep-alive", "cache-control": "no-cache", "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/53.0.2785.143 Safari/537.36", "postman-token": "9817ea4d-ad9d-b2fc-7685-9dff1a1bc193", "accept": "*/*", "accept-encoding": "gzip, deflate, sdch", "accept-language": "zh-CN,zh;q=0.8" }, "response": { "X-Application-Context": "hello:dev:8881", "Content-Type": "application/json;charset=UTF-8", "Transfer-Encoding": "chunked", "Date": "Sat, 24 Dec 2016 09:00:22 GMT", "status": "200" } } } }, ... ]
操作控制类
仔细的读者可能会发现,我们在“初识Actuator”时运行示例的控制台中输出的所有监控端点,
已经在介绍应用配置类端点和度量指标类端点时都讲解完了。
那么还有哪些是操作控制类端点呢?
实际上,由于之前介绍的所有端点都是用来反映应用自身的属性或是运行中的状态,
相对于操作控制类端点没有那么敏感,所以他们默认都是启用的。
而操作控制类端点拥有更强大的控制能力,如果要使用它们的话,需要通过属性来配置开启。
在原生端点中,只提供了一个用来关闭应用的端点:/shutdown。我们可以通过如下配置开启它:
endpoints.shutdown.enabled=true
在配置了上述属性之后,只需要访问该应用的/shutdown端点就能实现关闭该应用的远程操作。
由于开放关闭应用的操作本身是一件非常危险的事,
所以真正在线上使用的时候,我们需要对其加入一定的保护机制,
比如:
定制Actuator的端点路径、整合Spring Security进行安全校验等。
http://www.open-open.com/lib/view/open1486282830132.html
SpringBoot
是为了简化Spring
应用的创建、运行、调试、部署等一系列问题而诞生的产物,自动装配的特性让我们可以更好的关注业务本身而不是外部的XML配置,我们只需遵循规范,引入相关的依赖就可以轻易的搭建出一个 WEB 工程
actuator
是spring boot
项目中非常强大一个功能,有助于对应用程序进行监视和管理,通过 restful api
请求来监管、审计、收集应用的运行情况,针对微服务而言它是必不可少的一个环节…
Endpoints
actuator
的核心部分,它用来监视应用程序及交互,spring-boot-actuator
中已经内置了非常多的 Endpoints(health、info、beans、httptrace、shutdown等等)
,同时也允许我们自己扩展自己的端点
Spring Boot 2.0
中的端点和之前的版本有较大不同,使用时需注意。另外端点的监控机制也有很大不同,启用了不代表可以直接访问,还需要将其暴露出来,传统的management.security
管理已被标记为不推荐。
内置Endpoints
id | desc | Sensitive |
---|---|---|
auditevents | 显示当前应用程序的审计事件信息 | Yes |
beans | 显示应用Spring Beans的完整列表 | Yes |
caches | 显示可用缓存信息 | Yes |
conditions | 显示自动装配类的状态及及应用信息 | Yes |
configprops | 显示所有 @ConfigurationProperties 列表 | Yes |
env | 显示 ConfigurableEnvironment 中的属性 | Yes |
flyway | 显示 Flyway 数据库迁移信息 | Yes |
health | 显示应用的健康信息(未认证只显示status,认证显示全部信息详情) | No |
info | 显示任意的应用信息(在资源文件写info.xxx即可) | No |
liquibase | 展示Liquibase 数据库迁移 | Yes |
metrics | 展示当前应用的 metrics 信息 | Yes |
mappings | 显示所有 @RequestMapping 路径集列表 | Yes |
scheduledtasks | 显示应用程序中的计划任务 | Yes |
sessions | 允许从Spring会话支持的会话存储中检索和删除用户会话。 | Yes |
shutdown | 允许应用以优雅的方式关闭(默认情况下不启用) | Yes |
threaddump | 执行一个线程dump | Yes |
httptrace | 显示HTTP跟踪信息(默认显示最后100个HTTP请求 - 响应交换) | Yes |
导入依赖
在 pom.xml
中添加 spring-boot-starter-actuator
的依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
注意事项
如果要访问info
接口想获取maven
中的属性内容请记得添加如下内容
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>build-info</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
属性配置
在 application.properties
文件中配置actuator
的相关配置,其中info
开头的属性,就是访问info
端点中显示的相关内容,值得注意的是Spring Boot2.x
中,默认只开放了info、health
两个端点,剩余的需要自己通过配置management.endpoints.web.exposure.include
属性来加载(有include
自然就有exclude
,不做详细概述了)。如果想单独操作某个端点可以使用management.endpoint.端点.enabled
属性进行启用或禁用
# 描述信息 info.blog-url=https://blog.csdn.net/liupeifeng3514 info.author=WaKengMaiNi info.version=@project.version@ # 加载所有的端点/默认只加载了 info / health management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always # 可以关闭指定的端点 management.endpoint.shutdown.enabled=false # 路径映射,将 health 路径映射成 rest_health 那么在访问 health 路径将为404,因为原路径已经变成 rest_health 了,一般情况下不建议使用 # management.endpoints.web.path-mapping.health=rest_health
简单测试
启动项目,访问 http://localhost:8080/actuator/info 看到如下内容代表配置成功
{
"blog-url": "https://blog.csdn.net/liupeifeng3514", "author": "WaKengMaiNi", "version": "0.0.1-SNAPSHOT" }
自定义 - 重点
上面讲了很多都是配置相关,以及自带的一些端点,在实际应用中有时候默认并不能满足我们的要求,比如Spring Boot
默认的健康端点就很有可能不能满足
默认装配 HealthIndicators
下列是依赖spring-boot-xxx-starter
后相关HealthIndicator
的实现(通过management.health.defaults.enabled
属性可以禁用它们),但想要获取一些额外的信息时,自定义的作用就体现出来了…
名称 | 描述 |
---|---|
CassandraHealthIndicator | 检查 Cassandra 数据库是否启动。 |
DiskSpaceHealthIndicator | 检查磁盘空间不足。 |
DataSourceHealthIndicator | 检查是否可以获得连接 DataSource。 |
ElasticsearchHealthIndicator | 检查 Elasticsearch 集群是否启动。 |
InfluxDbHealthIndicator | 检查 InfluxDB 服务器是否启动。 |
JmsHealthIndicator | 检查 JMS 代理是否启动。 |
MailHealthIndicator | 检查邮件服务器是否启动。 |
MongoHealthIndicator | 检查 Mongo 数据库是否启动。 |
Neo4jHealthIndicator | 检查 Neo4j 服务器是否启动。 |
RabbitHealthIndicator | 检查 Rabbit 服务器是否启动。 |
RedisHealthIndicator | 检查 Redis 服务器是否启动。 |
SolrHealthIndicator | 检查 Solr 服务器是否已启动。 |
健康端点(第一种方式)
实现HealthIndicator
接口,根据自己的需要判断返回的状态是UP
还是DOWN
,功能简单。
package com.lpf.chapter13.health; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; /** * <p>自定义健康端点</p> */ @Component("my1") public class MyHealthIndicator implements HealthIndicator { private static final String VERSION = "v1.0.0"; @Override public Health health() { int code = check(); if (code != 0) { Health.down().withDetail("code", code).withDetail("version", VERSION).build(); } return Health.up().withDetail("code", code) .withDetail("version", VERSION).up().build(); } private int check() { return 0; } }
简单测试
启动项目,访问 http://localhost:8080/actuator/health 看到如下内容代表配置成功
{
"status": "UP", "details": { "my1": { "status": "UP", "details": { "code": 0, "version": "v1.0.0" } }, "diskSpace": { "status": "UP", "details": { "total": 112090574848, "free": 54290890752, "threshold": 10485760 } } } }
健康端点(第二种方式)
继承AbstractHealthIndicator
抽象类,重写doHealthCheck
方法,功能比第一种要强大一点点,默认的DataSourceHealthIndicator
、 RedisHealthIndicator
都是这种写法,内容回调中还做了异常的处理。
package com.lpf.chapter13.health; import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health; import org.springframework.stereotype.Component; /** * <p>自定义健康端点</p> * <p>功能更加强大一点,DataSourceHealthIndicator / RedisHealthIndicator 都是这种写法</p> */ @Component("my2") public class MyAbstractHealthIndicator extends AbstractHealthIndicator { private static final String VERSION = "v1.0.0"; @Override protected void doHealthCheck(Health.Builder builder) throws Exception { int code = check(); if (code != 0) { builder.down().withDetail("code", code).withDetail("version", VERSION).build(); } builder.withDetail("code", code) .withDetail("version", VERSION).up().build(); } private int check() { return 0; } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
简单测试
启动项目,访问 http://localhost:8080/actuator/health 看到如下内容代表配置成功
{
"status": "UP", "details": { "my2": { "status": "UP", "details": { "code": 0, "version": "v1.0.0" } }, "my1": {...}, "diskSpace": {...} } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
定义自己的端点
上面介绍的 info
、health
都是spring-boot-actuator
内置的,真正要实现自己的端点还得通过@Endpoint
、 @ReadOperation
、@WriteOperation
、@DeleteOperation
。
注解介绍
不同请求的操作,调用时缺少必需参数,或者使用无法转换为所需类型的参数,则不会调用操作方法,响应状态将为400(错误请求)
@Endpoint
构建 rest api 的唯一路径@ReadOperation
GET请求,响应状态为 200 如果没有返回值响应 404(资源未找到)@WriteOperation
POST请求,响应状态为 200 如果没有返回值响应 204(无响应内容)@DeleteOperation
DELETE请求,响应状态为 200 如果没有返回值响应 204(无响应内容)
package com.lpf.chapter13.endpoint; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import java.util.HashMap; import java.util.Map; /** * <p>@Endpoint 是构建 rest 的唯一路径 </p> * 顾名思义就是不同请求的操作,调用时缺少必需参数,或者使用无法转换为所需类型的参数,则不会调用操作方法,响应状态将为400(错误请求) * <P>@ReadOperation = GET 响应状态为 200 如果没有返回值响应 404(资源未找到) </P> * <P>@WriteOperation = POST 响应状态为 200 如果没有返回值响应 204(无响应内容) </P> * <P>@DeleteOperation = DELETE 响应状态为 200 如果没有返回值响应 204(无响应内容) </P> */ @Endpoint(id = "lpf") public class MyEndPoint { @ReadOperation public Map<String, String> hello() { Map<String, String> result = new HashMap<>(); result.put("author", "lpf"); result.put("age", "24"); result.put("email", "XXXXXXXXXX@qq.com"); return result; } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
以为这就大功告成了吗,现实告诉我的是spring-boot
默认是不认识这玩意的,得申明成一个Bean
(请看 主函数
)
主函数
package com.lpf.chapter13; import com.lpf.chapter13.endpoint.MyEndPoint; import org.springframework.boot.SpringApplication; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @SpringBootApplication public class Chapter13Application { public static void main(String[] args) { SpringApplication.run(Chapter13Application.class, args); } @Configuration static class MyEndpointConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint public MyEndPoint myEndPoint() { return new MyEndPoint(); } } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
测试
完成准备事项后,启动Chapter13Application
访问 http://localhost:8080/actuator/battcn 看到如下内容代表配置成功…
{
"author": "lpf", "age": "24", "email": "XXXXXXXXXX@qq.com" }
- 1
- 2
- 3
- 4
- 5
总结
参考文档:https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready
目前很多大佬都写过关于 SpringBoot
的教程了,如有雷同,请多多包涵,本教程基于最新的 spring-boot-starter-parent:2.0.2.RELEASE
编写,包括新版本的特性都会一起介绍…
https://blog.csdn.net/liupeifeng3514/article/details/80558414
前言
主要是完成微服务的监控,完成监控治理。可以查看微服务间的数据处理和调用,当它们之间出现了异常,就可以快速定位到出现问题的地方。
springboot - version: 2.0
正文
依赖
maven 项目 在 pom.xml 文件中加入 actuator 的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
1
2
3
4
使用 Gradle 构建:
dependencies {
compile("org.springframework.boot:spring-boot-starter-actuator")
}
1
2
3
配置
需要注意的是 Spring Boot 2.0 相对于上个版本, Actuator 发生很多变化,
keys 的配置改变
旧的属性 新的属性
endpoints.<id>.* management.endpoint.<id>.*
endpoints.cors.* management.endpoints.web.cors.*
endpoints.jmx.* management.endpoints.jmx.*
management.address management.server.address
management.context-path management.server.servlet.context-path
management.ssl.* management.server.ssl.*
management.port management.server.port
基本路径
所有 endpoints 默认情况下都已移至 /actuator。就是多了跟路径 actuator ;
上个版本中的 management/context-path: 和 management/port: 改为 :
management:
server:
port: 8004
servlet:
context-path: /xxx # 只有在设置了 management.server.port 时才有效
1
2
3
4
5
另外,您还可以使用新的单独属性 management.endpoints.web.base-path 为管理端点设置基本路径。
例如,如果你设置management.server.servlet.context-path=/management和management.endpoints.web.base-path=/application,你就可以在下面的路径到达终点健康:/management/application/health。
如果你想恢复 1.x 的行为(即具有/health代替/actuator/health),设置以下属性:management.endpoints.web.base-path=/
ENDPOINTS
1.X 的时候属性:
HTTP 方法 路径 描述
GET /autoconfig 提供了一份自动配置报告,记录哪些自动配置条件通过了,哪些没通过
GET /configprops 描述配置属性(包含默认值)如何注入Bean
GET /beans 描述应用程序上下文里全部的Bean,以及它们的关系
GET /dump 获取线程活动的快照
GET /env 获取全部环境属性
GET /env/{name} 根据名称获取特定的环境属性值
GET /health 报告应用程序的健康指标,这些值由HealthIndicator的实现类提供
GET /info 获取应用程序的定制信息,这些信息由info打头的属性提供
GET /mappings 描述全部的URI路径,以及它们和控制器(包含Actuator端点)的映射关系
GET /metrics 报告各种应用程序度量信息,比如内存用量和HTTP请求计数
GET /metrics/{name} 报告指定名称的应用程序度量值
POST /shutdown 关闭应用程序,要求endpoints.shutdown.enabled设置为true
GET /trace 提供基本的HTTP请求跟踪信息(时间戳、HTTP头等)
2.0 部分更改:
1.x 端点 2.0 端点(改变)
/actuator 不再可用。 但是,在 management.endpoints.web.base-path 的根目录中有一个映射,它提供了到所有暴露端点的链接。
/auditevents 该after参数不再需要
/autoconfig 重命名为 /conditions
/docs 不再可用
/health 现在有一个 management.endpoint.health.show-details 选项 never, always, when-authenticated,而不是依靠 sensitive 标志来确定 health 端点是否必须显示全部细节。 默认情况下,/actuator/health公开并且不显示细节。
/trace 重命名为 /httptrace
默认端点 path 前面多了一级 /actuator 。
同时注意只有端点/health和/info端点是暴露的。
Property Default
management.endpoints.jmx.exposure.exclude
management.endpoints.jmx.exposure.include *
management.endpoints.web.exposure.exclude
management.endpoints.web.exposure.include info, health
1. 您可以按如下方式公开所有端点:management.endpoints.web.exposure.include=*
2. 您可以通过以下方式显式启用/shutdown端点:management.endpoint.shutdown.enabled=true
3. 要公开所有(已启用)网络端点除env端点之外:
management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env
1
2
例如:
我现在开启所有的端点:
management:
endpoints:
web:
exposure:
include: "*" # * 在yaml 文件属于关键字
1
2
3
4
5
执行 localhost:${port}/actuator,可以看到所有可以执行查看的端点监控的 Url,然后我们尝试执行关闭应用进程的指令:shutdown:
端点格式
/actuator/mappings 端点大改变
JSON 格式已经更改为现在正确地包含有关上下文层次结构,多个DispatcherServlets,部署的 Servlet 和 Servlet 过滤器的信息。详情请参阅#9979。
Actuator API 文档的相关部分提供了一个示例文档。
/actuator/httptrace 端点大改变
响应的结构已经过改进,以反映端点关注跟踪 HTTP 请求 - 响应交换的情况。
总结
主要是 Spring Boot 2.0 版本升级在 Actuator 上面有许多改动,需要记录下。
参考文章
Part V. Spring Boot Actuator: Production-ready features
Spring Boot 2.0系列文章(一):Spring Boot 2.0 迁移指南
---------------------
作者:KronChan
来源:CSDN
原文:https://blog.csdn.net/qq_35915384/article/details/80203768
版权声明:本文为博主原创文章,转载请附上博文链接!