1.添加依赖
<!-- actuator依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2.敏感信息加密--引入security
<!-- security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3.资源配置
http://localhost:8080/health
1.加入用户信息
security:
user:
name: admin
password: 123456
2.基础配置
management:
# 一般启动独立端口(默认和应用端口一致),启用后源端口不可查
server:
port: 8080
endpoints:
web:
# 默认前缀路径,可修改
base-path: /actuator
exposure:
# 向外暴露的端点,可用通配符('*',需要单引号)
include: health,info,metrics
# 排除暴露的端点
exclude: env,heapdump
3.配置 info 开头的属性
info:
contact:
email: 2769****13@qq.com
phone: 123456789
description: actuator-test-application
访问localhost:8080/info接口,泄露springboot项目信息。
4.健康指标
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class RocketMQHealthIndicator implements HealthIndicator {
@Override
public Health health() {
int errorCode = check();
if (errorCode != 0) {
return Health.down().withDetail("Error Code", errorCode).build();
}
return Health.up().build();
}
private int check() {
// 自定义健康检查
return 0;
}
}
访问localhost:8080/env
接口,泄露springboot环境变量信息
5.指标端点 metrics
4.隐藏端点
management:
server:
port: 8080
security:
enabled: true
endpoint:
shutdown:
enabled: true
web:
exposure:
include: "*"
exclude: info,health,test
base-path: /actuator
path-mapping:
prometheus: metrics
health: /health
metrics: /metrics
5.配置类
ps:springboot的版本为2.的版本,否则EndpointRequest没有包
# 需要Security验证的actuator端点名,多个端点之间使用,隔开。
actuator:
security:
endpoints: info,prometheus,test
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${actuator.security.endpoints:#{null}}")
private String endpoints;
@Value("${spring.security.user.name}")
public String userName;
@Value("${spring.security.user.password}")
public String password;
@Value("${spring.security.user.roles}")
public String role;
@Override
protected void configure(HttpSecurity http) throws Exception {
// 方式1:开放的actuator端点全部都验证
// http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests()
// .anyRequest().authenticated().and().httpBasic();
// 方式2:仅验证名单中的actuator端点
http.requestMatcher(EndpointRequest.to(transformEndpoints(endpoints))).authorizeRequests()
.anyRequest().authenticated().and().httpBasic();
}
private String[] transformEndpoints(String endpoints) {
// isEmpty判空方法
if (ObjectUtils.isEmpty(endpoints)) {
return new String[0];
}
return endpoints.split(",");
}
}