项目监控
Spring Boot Actuator
- Endpoints:监控应用的入口,Spring Boot内置了很多端点,也支持自定义端点。
- 监控方式:HTTP 或 JMX。
- 访问路径:例如“/actuator/health”(是使用http访问 端点,所用的路径,health是访问端点的id)
- 注意事项:按需配置暴露的端点,并对所有的端点进行权限控制。(暴露端点会影响性能,而且会有被别人窃取的风险。所以按需配置就行。不进行权限控制的话,别人通过访问端点就可以直接访问底层信息,很危险)
为什么要对项目进行监控
SpringBoot 的开发难度大大降低,但是底层操作很复杂。
使用
1、导包,默认暴露两个端点
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2、配置
# actuator
management.endpoints.web.exposure.include=* // 暴露所有端点
management.endpoints.web.exposure.exclude=info,caches // 排除个别端点
3、内置端点查看
localhost:8080/community/actuator/health/beans
查看所有的Bean
4、自定义端点
package com.nowcoder.community.actuator;
...
@Component
@Endpoint(id = "database")
public class DatabaseEndpoint {
private static final Logger logger = LoggerFactory.getLogger(DatabaseEndpoint.class);
//连接池,由Spring管理,注入即可
@Autowired
private DataSource dataSource;
// @ReadOperation 表示该方法通过 get请求访问
@ReadOperation
public String checkConnection() {
try (
Connection conn = dataSource.getConnection(); // 尝试获取连接,编译时会自动加finally把初始化的资源关闭
) {
return CommunityUtil.getJSONString(0, "获取连接成功!"); // 返回json字符串
} catch (SQLException e) {
logger.error("获取连接失败:" + e.getMessage());
return CommunityUtil.getJSONString(1, "获取连接失败!");
}
}
}
权限管理
直接使用Spring Security即可,设置 actuator/** 路径只有管理员才能访问
@Override
protected void configure(HttpSecurity http) throws Exception {
// 授权
http.authorizeRequests()
.antMatchers(
"/user/setting",
"/user/upload",
"/discuss/add",
"/comment/add/**",
"/letter/**",
"/notice/**",
"/like",
"/follow",
"/unfollow"
)
.hasAnyAuthority(
AUTHORITY_USER,
AUTHORITY_ADMIN,
AUTHORITY_MODERATOR
)
.antMatchers(
"/discuss/top",
"/discuss/wonderful"
)
.hasAnyAuthority(
AUTHORITY_MODERATOR
)
.antMatchers(
"/discuss/delete",
"/data/**",
"/actuator/**" // 在这里添加
)
.hasAnyAuthority(
AUTHORITY_ADMIN
)
.anyRequest().permitAll()