Article Directory
One, know Endpoint
Spring Boot Actuator provides some actuator endpoints to monitor and interact with your application. For example, when a project fails, it will automatically alarm, monitor content, operating status, etc., and give early warning.
Official reference API: click for reference
Two, simple example
(1) Add dependency
(2) Except for the shutdown port which is closed by default, other ports are open by default
Need to understand that does not mean the end to open end exposed, exposure is not necessarily open, only the default exposure endpoint info
andhealth
(3) Start the project to view the exposed endpoints:
#默认是关闭的,可以手动开启
management.endpoint.shutdown.enabled=true
#如果不想全部开启,也可以关闭默认配置,手动开启自己需要的
#management.endpoints.enabled-by-default=false
This is equivalent to all my endpoints are turned on: you can see that it exposes two endpoints, health
andinfo
View health:
View info:
You can configure the endpoint exposure yourself: you can see that the default is only health and info
#配置端点暴露,* 表示暴露所有端点
management.endpoints.web.exposure.include=*
As you can see, all endpoints are exposed at this time:
At this time, try to make a POST request and perform the shutdown operation:
because it is not safe to access the endpoint directly, you need to add a security to protect the endpoint
Three, introduce springsecurity to protect endpoints
(1) Add security dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
(2) Configure Security
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint())
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
application.properties
#配置 security
spring.security.user.name=yolo
spring.security.user.password=123
spring.security.user.roles=ADMIN
(3) Start the project and access the test. If
direct access is found, it will report 401, and you need to verify the login before accessing:
Successful access:
(4) Path configuration
Previous visits, no actuator
, for example, visits health
were direct:http://localhost:8080/health
, Starting with SpringBoot2, there is one more in the middle actuator
.
Of course, if you visit, you don’t want the middle one actuator
( this is generally not recommended):
#代替掉 actuator
management.endpoints.web.base-path=/yolo
#也可以自定义端点的名称
management.endpoints.web.path-mapping.health=yolo-health
Successful access:
(5) Support cross-domain
#指定允许的域
management.endpoints.web.cors.allowed-origins=http://localhost:8081
#指定允许的方法
management.endpoints.web.cors.allowed-methods=GET,POST