SpringBoot - Actuator应用监控使用详解2(端点保护、响应缓存、路径映射、CORS跨域)
三、端点保护
1,使用 Spring Security 进行端点保护
(1)如果端点需要对外提供服务,最好能够将这些端点保护起来。这里我们使用 Spring Security 保护,首先添加相关依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
(2)然后添加 Spring Security 配置,下面代码表示所有的 Endpoint 都需要具有 ADMIN 角色才能访问,同时开启 HttpBasic 认证。
注意:EndpointRequest.toAnyEndpoint() 表示匹配所有的 Endpoint,例如 shudown、mapping、health 等,但是不包括开发者通过 @RequestMapping 注解定义的接口。
@Configuration public class ActuatorSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.requestMatcher(EndpointRequest.toAnyEndpoint()) .authorizeRequests() .anyRequest().hasRole("ADMIN") .and() .httpBasic(); } }
(3)用户账号这边为了方便演示,Spring Security 就不连接数据库了,直接在 application.properties 中定义一个用户进行测试:
spring.security.user.name=hangge spring.security.user.password=123 spring.security.user.roles=ADMIN
2,运行测试
我们使用浏览器访问 http://localhost:8080/actuator/health 端点接口,会先弹出个登录框,只有登录后才能访问。
四、端点响应缓存
对于一些不带参数的端点请求会自动进行缓存,我们可以通过如下方式配置缓存时间,下面配置表示 beans 端点的缓存时间为 100s
management.endpoint.beans.cache.time-to-live=100s
注意:如果端点添加了 Spring Security 保护,此时 Principal 会被视为端点的输入,因此端点响应将不会被缓存。
五、路径映射
(1)默认情况下所有端点都暴露在“/actuator”路径下,比如 health 端点的访问路径是“/actuator/health”:(2)如果需要对端点路径进行定制,可通过如下配置进行:
- 第一行配置表示将“/actuator”修改成“/”,也就是说所有端点访问路径都会失去“/actuator”前缀。
- 第二行配置表示将“health”修改成“healthcheck”
management.endpoints.web.base-path=/ management.endpoints.web.path-mapping.health=healthcheck
(3)经过上面配置以后,health 端点对访问路径就变成了“/healthcheck”
六、CORS 跨域支持
所有端点默认都没有开启跨域,我们可以通过如下配置快速开启 CORS 支持,进而实现跨域。下面配置表示允许端点处理来自 http://localhost:8081 地址的请求,允许的请求方法为 GET 和 POST:
management.endpoints.web.cors.allowed-origins=http://localhost:8081 management.endpoints.web.cors.allowed-methods=GET,POST