一篇文章带你入门 SpringBoot 中的 Endpoints

一、认识 Endpoint

Spring Boot Actuator 提供了一些 actuator endpoint 来实现对你的应用程序进行监控和交互,比如在项目出错时,自动报警,监控内容,运行状况等,提前预警。

官方参考 API:点击参考

二、简单示例

(1)加入依赖

在这里插入图片描述
(2)除了 shutdown 端口默认是关闭,其他端口都是默认开启的

在这里插入图片描述
需要明白,端点开启并不意味着端点暴露,开启不一定暴露,默认的暴露端点只有 infohealth

在这里插入图片描述
(3)启动项目查看暴露端点:

#默认是关闭的,可以手动开启
management.endpoint.shutdown.enabled=true
#如果不想全部开启,也可以关闭默认配置,手动开启自己需要的
#management.endpoints.enabled-by-default=false

这里相当于我的所有端点都已开启:可以看到也就暴露出来了两个端点,healthinfo

在这里插入图片描述
查看 health:

在这里插入图片描述
查看 info:

在这里插入图片描述
可以自己配置端点暴露:可以看到默认是只有 health 和 info

在这里插入图片描述

#配置端点暴露,* 表示暴露所有端点
management.endpoints.web.exposure.include=*

可以看到,此时所有端点都暴露了:

在这里插入图片描述
此时尝试下 POST 请求,执行 shutdown 操作:
在这里插入图片描述
在这里插入图片描述
由于直接对端点进行访问,不安全,所以需要加个 security 将端点保护起来

三、引入 springsecurity 保护端点

(1)加入 security 依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

(2)配置 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)启动项目,访问测试
发现直接访问,会报 401,需要先验证登录再访问:

在这里插入图片描述
访问成功:

在这里插入图片描述
(4)路径配置
以前访问,没有 actuator,比如访问 health,是直接:http://localhost:8080/health,从 SpringBoot2 开始,中间多了个 actuator

当然如果访问时,不想要中间这个 actuator(一般不建议这样操作):

#代替掉 actuator
management.endpoints.web.base-path=/yolo
#也可以自定义端点的名称
management.endpoints.web.path-mapping.health=yolo-health

访问成功:

在这里插入图片描述
(5)支持跨域

#指定允许的域
management.endpoints.web.cors.allowed-origins=http://localhost:8081
#指定允许的方法
management.endpoints.web.cors.allowed-methods=GET,POST

猜你喜欢

转载自blog.csdn.net/nanhuaibeian/article/details/109290199