问答平台(8),项目监控

Spring Boot Actuator

1
2
3
4
- Endpoints: 监控应用的入口,Spring Boot内置了很多端点,也支持自定义端点。
- 监控方式: HTTP 或 JMX。
- 访问路径: 例如 "/actuator/health"。
- 注意事项: 按需配置暴露的端点,并对所有端点进行权限控制。

导入依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

访问默认端点

http://localhost:8080/actuator/health
actuator-health-图示
http://localhost:8080/actuator/info
actuator-info-图示

配置文件

  • application-develop.properties: 增加内容
    1
    2
    3
    # actuator
    management.endpoints.web.exposure.include=*
    management.endpoints.web.exposure.exclude=info,caches

访问内置端点

  • 访问链接
    1
    2
    3
    4
    5
    localhost:8080/community/actuator/info
    localhost:8080/community/actuator/cache
    localhost:8080/community/actuator/health
    localhost:8080/community/actuator/beans
    localhost:8080/community/actuator/loggers

自定义端点

  • DatabaseEndpoint: 新增
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    @Component
    @Endpoint(id = "database")
    public class DatabaseEndpoint {

    private static final Logger logger = LoggerFactory.getLogger(DatabaseEndpoint.class);

    @Autowired
    private DataSource dataSource;

    @ReadOperation
    public String checkConnection() {
    try (
    Connection conn = dataSource.getConnection();
    ) {
    return CommunityUtil.getJSONString(0, "获取连接成功!");
    } catch (SQLException e) {
    logger.error("获取连接失败: " + e.getMessage());
    return CommunityUtil.getJSONString(1, "获取连接失败!");
    }
    }
    }

权限管理

  • SecurityConfig: 修改
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    // 授权
    http.authorizeRequests()
    .antMatchers(
    "/discuss/delete",
    "/data/**",
    "/actuator/**"
    )
    .hasAnyAuthority(
    AUTHORITY_ADMIN
    )
    .anyRequest().permitAll()
    .and().csrf().disable();

    // 权限不够时的处理(略)
    }

结果展示

普通用户

普通用户访问database-图示

管理员

管理员访问database-图示


问答平台(8),项目监控
https://lcf163.github.io/2020/06/23/问答平台(8),项目监控/
作者
乘风的小站
发布于
2020年6月23日
许可协议