Spring Boot Actuator

文章目录

Spring Boot Actuator

Spring Boot Actuator 在Spring Boot第一个版本发布的时候就有了,它为Spring Boot提供了一系列产品级的特性:监控应用程序,收集元数据,运行情况或者数据库状态等。

使用Spring Boot Actuator我们可以直接使用这些特性而不需要自己去实现,它是用HTTP或者JMX来和外界交互。

开始使用Spring Boot Actuator

要想使用Spring Boot Actuator,需要添加如下依赖:

1<dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-actuator</artifactId> 4</dependency>

开始使用Actuator

配好上面的依赖之后,我们使用下面的主程序入口就可以使用Actuator了:

1@SpringBootApplication 2public class ActuatorApp { 3 public static void main(String[] args) { 4 SpringApplication.run(ActuatorApp.class, args); 5 } 6}

启动应用程序,访问http://localhost:8080/actuator:

{"_links":{"self":{"href":"http://localhost:8080/actuator","templated":false},"health":{"href":"http://localhost:8080/actuator/health","templated":false},"health-path":{"href":"http://localhost:8080/actuator/health/{*path}","templated":true},"info":{"href":"http://localhost:8080/actuator/info","templated":false}}}

我们可以看到actuator默认开启了两个入口:/health和/info。

如果我们在配置文件里面这样配置,则可以开启actuator所有的入口:

management.endpoints.web.exposure.include=*

重启应用程序,再次访问http://localhost:8080/actuator:

{"_links":{"self":{"href":"http://localhost:8080/actuator","templated":false},"beans":{"href":"http://localhost:8080/actuator/beans","templated":false},"caches-cache":{"href":"http://localhost:8080/actuator/caches/{cache}","templated":true},"caches":{"href":"http://localhost:8080/actuator/caches","templated":false},"health":{"href":"http://localhost:8080/actuator/health","templated":false},"health-path":{"href":"http://localhost:8080/actuator/health/{*path}","templated":true},"info":{"href":"http://localhost:8080/actuator/info","templated":false},"conditions":{"href":"http://localhost:8080/actuator/conditions","templated":false},"configprops":{"href":"http://localhost:8080/actuator/configprops","templated":false},"env":{"href":"http://localhost:8080/actuator/env","templated":false},"env-toMatch":{"href":"http://localhost:8080/actuator/env/{toMatch}","templated":true},"loggers-name":{"href":"http://localhost:8080/actuator/loggers/{name}","templated":true},"loggers":{"href":"http://localhost:8080/actuator/loggers","templated":false},"heapdump":{"href":"http://localhost:8080/actuator/heapdump","templated":false},"threaddump":{"href":"http://localhost:8080/actuator/threaddump","templated":false},"metrics":{"href":"http://localhost:8080/actuator/metrics","templated":false},"metrics-requiredMetricName":{"href":"http://localhost:8080/actuator/metrics/{requiredMetricName}","templated":true},"scheduledtasks":{"href":"http://localhost:8080/actuator/scheduledtasks","templated":false},"mappings":{"href":"http://localhost:8080/actuator/mappings","templated":false}}}

我们可以看到actuator暴露的所有入口。

Health Indicators

Health入口是用来监控组件的状态的,通过上面的入口,我们可以看到Health的入口如下:

"health":{"href":"http://localhost:8080/actuator/health","templated":false},"health-path":{"href":"http://localhost:8080/actuator/health/{*path}","templated":true},

有两个入口,一个是总体的health,一个是具体的health-path。

我们访问一下http://localhost:8080/actuator/health:

{"status":"UP"}

上面的结果实际上是隐藏了具体的信息,我们可以通过设置

management.endpoint.health.show-details=ALWAYS

来开启详情,开启之后访问如下:

{"status":"UP","components":{"db":{"status":"UP","details":{"database":"H2","result":1,"validationQuery":"SELECT 1"}},"diskSpace":{"status":"UP","details":{"total":250685575168,"free":12428898304,"threshold":10485760}},"ping":{"status":"UP"}}}

其中的components就是health-path,我们可以访问具体的某一个components如http://localhost:8080/actuator/health/db:

{"status":"UP","details":{"database":"H2","result":1,"validationQuery":"SELECT 1"}}

就可以看到具体某一个component的信息。

这些Health components的信息都是收集实现了HealthIndicator接口的bean来的。

我们看下怎么自定义HealthIndicator:

1@Component 2public class CustHealthIndicator implements HealthIndicator { 3 4 @Override 5 public Health health() { 6 int errorCode = check(); // perform some specific health check 7 if (errorCode != 0) { 8 return Health.down() 9 .withDetail("Error Code", errorCode).build(); 10 } 11 return Health.up().build(); 12 } 13 14 public int check() { 15 // Our logic to check health 16 return 0; 17 } 18}

再次查看http://localhost:8080/actuator/health, 我们会发现多了一个Cust的组件:

"components":{"cust":{"status":"UP"} }

在Spring Boot 2.X之后,Spring添加了React的支持,我们可以添加ReactiveHealthIndicator如下:

1@Component 2public class DownstreamServiceHealthIndicator implements ReactiveHealthIndicator { 3 4 @Override 5 public Mono<Health> health() { 6 return checkDownstreamServiceHealth().onErrorResume( 7 ex -> Mono.just(new Health.Builder().down(ex).build()) 8 ); 9 } 10 11 private Mono<Health> checkDownstreamServiceHealth() { 12 // we could use WebClient to check health reactively 13 return Mono.just(new Health.Builder().up().build()); 14 } 15}

再次查看http://localhost:8080/actuator/health,可以看到又多了一个组件:

"downstreamService":{"status":"UP"}

/info 入口

info显示了App的大概信息,默认情况下是空的。我们可以这样自定义:

1info.app.name=Spring Sample Application 2info.app.description=This is my first spring boot application 3info.app.version=1.0.0

查看:http://localhost:8080/actuator/info

{"app":{"name":"Spring Sample Application","description":"This is my first spring boot application","version":"1.0.0"}}

/metrics入口

/metrics提供了JVM和操作系统的一些信息,我们看下metrics的目录,访问:http://localhost:8080/actuator/metrics:

{"names":["jvm.memory.max","jvm.threads.states","jdbc.connections.active","process.files.max","jvm.gc.memory.promoted","system.load.average.1m","jvm.memory.used","jvm.gc.max.data.size","jdbc.connections.max","jdbc.connections.min","jvm.gc.pause","jvm.memory.committed","system.cpu.count","logback.events","http.server.requests","jvm.buffer.memory.used","tomcat.sessions.created","jvm.threads.daemon","system.cpu.usage","jvm.gc.memory.allocated","hikaricp.connections.idle","hikaricp.connections.pending","jdbc.connections.idle","tomcat.sessions.expired","hikaricp.connections","jvm.threads.live","jvm.threads.peak","hikaricp.connections.active","hikaricp.connections.creation","process.uptime","tomcat.sessions.rejected","process.cpu.usage","jvm.classes.loaded","hikaricp.connections.max","hikaricp.connections.min","jvm.classes.unloaded","tomcat.sessions.active.current","tomcat.sessions.alive.max","jvm.gc.live.data.size","hikaricp.connections.usage","hikaricp.connections.timeout","process.files.open","jvm.buffer.count","jvm.buffer.total.capacity","tomcat.sessions.active.max","hikaricp.connections.acquire","process.start.time"]}

访问其中具体的某一个组件如下http://localhost:8080/actuator/metrics/jvm.memory.max:

{"name":"jvm.memory.max","description":"The maximum amount of memory in bytes that can be used for memory management","baseUnit":"bytes","measurements":[{"statistic":"VALUE","value":3.456106495E9}],"availableTags":[{"tag":"area","values":["heap","nonheap"]},{"tag":"id","values":["Compressed Class Space","PS Survivor Space","PS Old Gen","Metaspace","PS Eden Space","Code Cache"]}]}

Spring Boot 2.X 的metrics是通过Micrometer来实现的,Spring Boot会自动注册MeterRegistry。 有关Micrometer和Spring Boot的结合使用我们会在后面的文章中详细讲解。

自定义Endpoint

Spring Boot的Endpoint也是可以自定义的:

1@Component 2@Endpoint(id = "features") 3public class FeaturesEndpoint { 4 5 private Map<String, String> features = new ConcurrentHashMap<>(); 6 7 @ReadOperation 8 public Map<String, String> features() { 9 return features; 10 } 11 12 @ReadOperation 13 public String feature(@Selector String name) { 14 return features.get(name); 15 } 16 17 @WriteOperation 18 public void configureFeature(@Selector String name, String value) { 19 features.put(name, value); 20 } 21 22 @DeleteOperation 23 public void deleteFeature(@Selector String name) { 24 features.remove(name); 25 } 26 27}

访问http://localhost:8080/actuator/, 我们会发现多了一个入口: http://localhost:8080/actuator/features/

上面的代码中@ReadOperation对应的是GET, @WriteOperation对应的是PUT,@DeleteOperation对应的是DELETE。

@Selector后面对应的是路径参数, 比如我们可以这样调用configureFeature方法:

1POST /actuator/features/abc HTTP/1.1 2Host: localhost:8080 3Content-Type: application/json 4User-Agent: PostmanRuntime/7.18.0 5Accept: */* 6Cache-Control: no-cache 7Postman-Token: dbb46150-9652-4a4a-95cb-3a68c9aa8544,8a033af4-c199-4232-953b-d22dad78c804 8Host: localhost:8080 9Accept-Encoding: gzip, deflate 10Content-Length: 15 11Connection: keep-alive 12cache-control: no-cache 13 14{"value":true}

注意,这里的请求BODY是以JSON形式提供的:

{"value":true}

请求URL:/actuator/features/abc 中的abc就是@Selector 中的 name。

我们再看一下GET请求:

http://localhost:8080/actuator/features/

{"abc":"true"}

这个就是我们之前PUT进去的值。

扩展现有的Endpoints

我们可以使用@EndpointExtension (@EndpointWebExtension或者@EndpointJmxExtension)来实现对现有EndPoint的扩展:

1@Component 2@EndpointWebExtension(endpoint = InfoEndpoint.class) 3public class InfoWebEndpointExtension { 4 5 private InfoEndpoint delegate; 6 7 // standard constructor 8 9 @ReadOperation 10 public WebEndpointResponse<Map> info() { 11 Map<String, Object> info = this.delegate.info(); 12 Integer status = getStatus(info); 13 return new WebEndpointResponse<>(info, status); 14 } 15 16 private Integer getStatus(Map<String, Object> info) { 17 // return 5xx if this is a snapshot 18 return 200; 19 } 20}

上面的例子扩展了InfoEndpoint。

本文所提到的例子可以参考:https://github.com/ddean2009/learn-springboot2/tree/master/springboot-actuator

更多教程请参考 flydean的博客

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )