Spring Boot Actuator

Stella981
• 阅读 756

文章目录

Spring Boot Actuator

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

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

开始使用Spring Boot Actuator

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

开始使用Actuator

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

@SpringBootApplication
public class ActuatorApp {
    public static void main(String[] args) {
        SpringApplication.run(ActuatorApp.class, args);
    }
}

启动应用程序,访问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:

@Component
public class CustHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        int errorCode = check(); // perform some specific health check
        if (errorCode != 0) {
            return Health.down()
                    .withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }

    public int check() {
        // Our logic to check health
        return 0;
    }
}

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

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

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

@Component
public class DownstreamServiceHealthIndicator implements ReactiveHealthIndicator {

    @Override
    public Mono<Health> health() {
        return checkDownstreamServiceHealth().onErrorResume(
                ex -> Mono.just(new Health.Builder().down(ex).build())
        );
    }

    private Mono<Health> checkDownstreamServiceHealth() {
        // we could use WebClient to check health reactively
        return Mono.just(new Health.Builder().up().build());
    }
}

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

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

/info 入口

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

info.app.name=Spring Sample Application
info.app.description=This is my first spring boot application
info.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也是可以自定义的:

@Component
@Endpoint(id = "features")
public class FeaturesEndpoint {

    private Map<String, String> features = new ConcurrentHashMap<>();

    @ReadOperation
    public Map<String, String> features() {
        return features;
    }

    @ReadOperation
    public String feature(@Selector String name) {
        return features.get(name);
    }

    @WriteOperation
    public void configureFeature(@Selector String name, String value) {
        features.put(name, value);
    }

    @DeleteOperation
    public void deleteFeature(@Selector String name) {
        features.remove(name);
    }

}

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

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

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

POST /actuator/features/abc HTTP/1.1
Host: localhost:8080
Content-Type: application/json
User-Agent: PostmanRuntime/7.18.0
Accept: */*
Cache-Control: no-cache
Postman-Token: dbb46150-9652-4a4a-95cb-3a68c9aa8544,8a033af4-c199-4232-953b-d22dad78c804
Host: localhost:8080
Accept-Encoding: gzip, deflate
Content-Length: 15
Connection: keep-alive
cache-control: no-cache

{"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的扩展:

@Component
@EndpointWebExtension(endpoint = InfoEndpoint.class)
public class InfoWebEndpointExtension {
 
    private InfoEndpoint delegate;
 
    // standard constructor
 
    @ReadOperation
    public WebEndpointResponse<Map> info() {
        Map<String, Object> info = this.delegate.info();
        Integer status = getStatus(info);
        return new WebEndpointResponse<>(info, status);
    }
 
    private Integer getStatus(Map<String, Object> info) {
        // return 5xx if this is a snapshot
        return 200;
    }
}

上面的例子扩展了InfoEndpoint。

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

更多教程请参考 flydean的博客

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
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
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这