当前位置: 代码网 > it编程>编程语言>Java > Spring Boot Actuator入门指南

Spring Boot Actuator入门指南

2025年02月11日 Java 我要评论
spring boot actuatorspring boot actuator 在spring boot第一个版本发布的时候就有了,它为spring boot提供了一系列产品级的特性:监控应用程序,

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

到此这篇关于spring boot actuator的文章就介绍到这了,更多相关spring boot actuator内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com