当前位置: 首页 > 科技观察

SpringBootAdmin:一个轻量级的SpringBoot监控组件,用过的人都说的不错

时间:2023-03-12 16:21:06 科技观察

简介SpringbootAdmin是一个管理监控Springboot项目的组件。分为server和client,两端通过http进行通信。由于其轻量级的特性,它特别适用于中小型项目。效果图如下:服务器配置1.引入Springbootadmin和SpringSecurity依赖。de.codecentricspring-boot-admin-starter-server2.5.1org.springframework.bootspring-boot-starter-security2、配置相关属性。server:port:8080servlet:context-path:/serverspring:security:user:#admin用于服务器登录的帐户密码name:server123password:123456boot:admin:instance-auth:#Enableheaderverificationenabled:true#当server访问client接口,将使用以下配置生成授权default-user-name:"name_shishan"default-password:"pwd_shishan"3.配置@EnableAdminServer注解。@SpringBootApplication@Configuration@EnableAdminServerpublicclassServerApplication{publicstaticvoidmain(String[]args){SpringApplication.run(ServerApplication.class,args);}}经过以上3步,服务器就可以启动了。访问http://localhost:8080/server/,可以看到如下登录界面。可以使用yml文件中配置的账号密码登录。客户端配置1.在我们要监控的客户端添加如下依赖。de.codecentricspring-boot-admin-starter-client2.5.12.暴露监控接口和配置服务器地址。客户端启动后,会向配置的服务器发起注册申请。这时候为了安全也需要服务器端的账号密码进行验证。spring:boot:admin:client:#admin注册地址url:http://localhost:8080/server#configureadminaccountusername:server123password:123456admin:header:auth:name:"name_shishan"password:"pwd_shishan"#Exposed端口管理:endpoints:web:exposure:include:"*"3.对暴露的接口进行权限验证。由于我们暴露了监控接口,所以我们必须验证相关接口的权限,否则相关信息可能会泄露。接口上的权限过滤有很多选项,比如设置IP访问白名单,只允许admin服务器所在的服务器访问,或者配置相关的token等。接下来我们使用一个简单的接口过滤器来验证/actuator/**相关接口的权限。@ComponentpublicclassPathFilterimplementsFilter{@Value("${admin.header.auth.name}")privateStringusername;@Value("${admin.header.auth.password}")私有字符串密码;@OverridepublicvoiddoFilter(ServletRequestservletRequest,ServletResponseservletResponse,FilterChainfilterChain)抛出IOException,ServletException{HttpServletRequestrequest=(HttpServletRequest)servletRequest;HttpServletResponse响应=(HttpServletResponse)servletResponse;AntPathMatcherantPathMatcher=newAntPathMatcher();if(antPathMatcher.match("/actuator/**",request.getServletPath())){Stringauthorization=request.getHeader("authorization");if(StringUtils.hasText(authorization)){Stringtoken=Base64Utils.encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));if(authorization.equals("Basic"+token)){//允许令牌匹配filterChain.doFilter(request,servletResponse);返回;}}response.setContentType("application/json;charset=UTF-8");response.setStatus(HttpStatus.UNAUTHORIZED.value());response.getWriter().print("权限不足");返回;}//其他接口直接释放filterChain.doFilter(request,servletResponse);}}在这个filter中,检查了actuator相关接口的header参数,暴露出来的actuator接口只有通过验证才能访问。当然,如果我们使用SpringSecurity或者SaToken等第三方权限框架,我们也可以重写相关配置来完成权限的判断。原理是一样的。来看看最终的监控效果:最后,Springbootadmin除了通过普通http请求获取监控信息外,还支持通过注册中心获取相关信息,在其官方文档中也可以看到相关配置。