Spring Boot Actuator
(1)Endpoints:监控应用的入口,Spring Boot内置了很多端点,也支持自定义端点。
(2)监控方式:HTTP或JMX。
(3)访问路径:例如"/actuator/health"。
(4)注意事项:按需配置暴露的端点,并对所有端点进行权限控制。
在mvn库里搜spring boot actutor,把这个spring-boot-starter-actutor包粘贴到pom.xml。默认有20多个端点,几乎所有端点都是启用的,只有一个端点是禁用的(关闭服务器的post请求,一个后门,别启用了)。但只暴露了两个端点,其他端点要访问的话需要配置。
启动后,输入localhost:8080/community/actutor/health和localhost:8080/community/actutor/info。
在application.properties里添加配置
# actuator
#management.endpoints.web.exposure.include=beans,loggers
management.endpoints.web.exposure.include=*
#禁掉info,caches
management.endpoints.web.exposure.exclude=info,caches
新建actutor包,新建DatabaseEndpoint类,
@Component
@Endpoint(id="database")
public class DatabaseEndpoint {
private static final Logger logger = LoggerFactory.getLogger(DatabaseEndpoint.class);
//可通过连接池或连接参数(manager)获取连接,这里用连接池
@Autowired
private DataSource dataSource;
@ReadOperation //表示是用get请求来访问
public String checkConnection(){
try (
Connection conn = dataSource.getConnection();
){
return CommunityUtil.getJSONString(0,"获取连接成功!");
} catch (SQLException e) {
logger.error("获取连接失败:"+e.getMessage());
return CommunityUtil.getJSONString(1,"获取连接失败!");
}
}
}
然后就可以用localhost:8080/community/actutor/database来看数据库是否连接成功。
还要补充权限控制,在SecurityConfig类configure方法里添加
.hasAnyAuthority(
AUTHORITY_MODERATOR
) //版主才有置顶、加精的权限(与上面那个antMatchers关联)
.antMatchers(
"/discuss/delete",
"/data/**",
"/actuator/**"
)
这样就能实现只有管理员才能访问这个数据库监控。