Spring Boot 生产级的特性java
Spring Boot 有许多开箱即用的模块或者说插件,其中 spring-boot-actuator
提供了大量的生产级的特性。添加 spring-boot-starter-actuator
的 maven 依赖:web
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
Actuator 模块提供一系列的 HTTP 请求,这些请求都是 GET 类型的,不带任何请求参数,可用经过他们获取 Spring Boot 应用程序的相关信息。这些入口就是 端点 (Endpoint)spring
ID | 描述 |
---|---|
auditevents |
公开当前应用程序的审计事件信息 |
beans |
获取 Spring bean 的完整列表 |
caches |
获取可用的缓存 |
conditions |
显示自动配置类的评估和配置条件,以及它们匹配或不匹配的缘由。 |
configprops |
显示配置项信息(经过@ConfigurationProperties 配置) |
env |
获取 Spring 应用的环境变量信息 ConfigurableEnvironment |
flyway |
显示已应用的Flyway数据库迁移信息 |
health |
显示应用健康检查信息 |
httptrace |
显示HTTP跟踪信息(默认状况下,最新100个HTTP请求) |
info |
显示当前应用信息 |
integrationgraph |
显示 Spring 集成图 |
loggers |
显示和修改应用程序中记录器的配置 |
liquibase |
显示已应用的Liquibase数据库迁移的信息 |
metrics |
显示当前应用程序的“度量”指标信息 |
mappings |
显示全部@RequestMapping 的映射路径信息 |
scheduledtasks |
显示应用程序中的任务计划 |
sessions |
容许从Spring Session支持的会话存储中检索和删除用户会话。使用Spring Session对响应式Web应用程序的支持时不可用 |
shutdown |
容许应用程序正常关闭(默认状况下不开启这个端点) |
threaddump |
执行线程转储 |
访问这些端点须要 前缀 /actuator/
+ 加上端点ID(spring boot 2.0以后须要加上 /actuator/),如 health 端点映射路径为 /actuator/health
数据库
默认状况下,除 shutdown
的全部端点都是开启的,咱们能够根据实际状况自由的控制哪些端点启用,哪些关闭,甚至还能够修改默认的端点名称。浏览器
配置端点的启用缓存
management.endpoint.<id>.enabled
,如启用 shutdown
端点安全
management.endpoint.shutdown.enabled=true
若是想要端点启用是选择加入而不是选择退出,将management.endpoints.enabled-by-default
属性设置 为false
,并使用各个端点 enabled
属性从新加入。如下示例启用info
端点并禁用全部其余端点session
management.endpoints.enabled-by-default=false management.endpoint.info.enabled=true
咱们启动了 spring boot 以后,在浏览器地址栏中分别输入:app
http://localhost:8080/actuator/health
maven
http://localhost:8080/actuator/beans
前面说默认状况下大部分端点都是开启的,那为什么端点 health 是能够访问到的,而端点 beans 确不行呢?
缘由是这些端点每每显示的都是项目的敏感信息,默认状况下,在 Web 下,Spring Boot 只会暴露 info h和 health 这两个端点,其他的都不暴露
想要改变暴露的端点,要使用 include
和 exclude
属性
属性 | 默认 |
---|---|
management.endpoints.jmx.exposure.exclude |
|
management.endpoints.jmx.exposure.include |
* |
management.endpoints.web.exposure.exclude |
|
management.endpoints.web.exposure.include |
info, health |
为了让 Actuator 暴露端点,能够配置
management.endpoints.web.exposure.include=health,info,beans
这样就能够访问 beans 端点了(http://localhost:8080/actuator/beans
)
在默认状况下,Actuator 对敏感信息是除了health 和 info 端点, 其他端点都是不暴露的。虽然能够经过配置 application.properties 这样的方式能够进行访问,可是这样的方式从安全的角度来讲是很是不利的
可使用 Spring Security 配置用户和角色,来解决这些敏感信息的访问权限问题,引入spring-boot-starter-security , 而后配置用户和角色
@Configuration public class ActuatorSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests() .anyRequest().hasRole("ENDPOINT_ADMIN") .and() .httpBasic(); } }
上面的示例用于 EndpointRequest.toAnyEndpoint()
将请求与任何端点进行匹配,而后确保全部端点都具备该ENDPOINT_ADMIN
角色。其余几种匹配方法也可用EndpointRequest
这个时候能够配置application.properties:
management.endpoints.web.exposure.include=*
经过这样的配置就能够把全部的端点都暴露出来,只是在Spring Security 中,对应保护的端点需 要拥有对应的权限才能够进行访问