SpringBoot入坑指南之四:使用Spring Boot Admin进行服务监控

开篇

说个笑话:“你的代码没有Bug!”。 谁也不能保证自己的代码没有Bug,自己的代码能够100%满足业务性能要求,当线上的服务出问题后,如何快速定位问题、解决问题,这才是一个好程序猿的标志。 通俗一点说,就是快速地将自己挖的坑填平,最好没有其他人发现。

Spring Boot的服务监控

Spring Boot Actuator

Spring Boot开发之初已经充分考虑服务监控需求,提供了spring-boot-starter-actuator监控模块,在项目用依赖该模块就可以开启相应的监控endpoit。

常用的endpoit包括以下:

endpoints说明
beans所有的Spring Bean信息
health应用健康信息
metrics应用各方面性能指标
mappings应用所有的Request Mapping路径
heapdump下载内存快照

具体可参考 官方文档

Spring Boot Admin

目前常用Spring Boot Admin进行Spring Boot应用服务监控,它提供了一个简洁美观的监控页面,底层基于Spring Boot Actuator实现。 Spring Boot Admin包括客户端和服务端:

  • 客户端:即需监控的应用服务,依赖Spring Boot Admin客户端包,向服务端进行注册。
  • 服务端:提供服务端注册相关服务以及服务监控相关服务,2.0的UI页面使用vuejs开发。

实现示例

搭建服务端

  • 创建一个spring-boot-examples-admin-server项目,添加以下依赖:
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
        </dependency>

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

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

  • 新增一个配置类SecuritySecureConfig,基于Spring Security实现Admin Server的安全控制,参考代码如下:
/**
 * @author: cent
 * @email: 292462859@qq.com
 * @date: 2019/2/11.
 * @description: <p>
 * Security配置类,用于配置admin server的安全控制
 */
@Configuration
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
    private final String adminContextPath;

    public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
        this.adminContextPath = adminServerProperties.getContextPath();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 登录成功处理类
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(adminContextPath + "/");

        http.authorizeRequests()
                //静态文件允许访问
                .antMatchers(adminContextPath + "/assets/**").permitAll()
                //登录页面允许访问
                .antMatchers(adminContextPath + "/login").permitAll()
                //其他所有请求需要登录
                .anyRequest().authenticated()
                .and()
                //登录页面配置,用于替换security默认页面
                .formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()
                //登出页面配置,用于替换security默认页面
                .logout().logoutUrl(adminContextPath + "/logout").and()
                .httpBasic().and()
                .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .ignoringAntMatchers(
                        "/instances",
                        "/actuator/**"
                );
    }
}

  • 创建应用启动类,在类添加注解@EnableAdminServer启用Admin Server。
/**
 * @author: cent
 * @email: 292462859@qq.com
 * @date: 2019/2/11.
 * @description:
 */
@EnableAdminServer
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

  • 配置文件application.yml如下:
spring:
  application:
    name: spring-boot-examples-admin-server
  security:
    user:
      name: admin
      password: 123456

server:
  port: 8090

搭建客户端

  • 创建一个需监控的Spring Boot应用项目spring-boot-examples-admin-client,添加以下依赖:
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
        </dependency>  

  • 创建一个SecuritySecureConfig,实现Security相关逻辑,代码如下文: 由于Spring Boot Actuator模块自身并没有安全控制,如果不增加安全控制会存在安全风险,所以使用Spring Security模块实现安全控制,以下代码实现对actuator的endpoints进行安全校验拦截,其他访问则不拦截。需注意角色名ACTUATOR_ADMIN,后续配置需使用。
/**
 * @author: cent
 * @email: 292462859@qq.com
 * @date: 2019/2/11.
 * @description:
 */
@Configuration
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //拦截所有endpoint,拥有ACTUATOR_ADMIN角色可访问,否则需登录
                .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ACTUATOR_ADMIN")
                //静态文件允许访问
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
                //根路径允许访问
                .antMatchers("/").permitAll()
                //所有请求路径可以访问
                .antMatchers("/**").permitAll()
                .and().httpBasic();
    }
}

  • 应用配置文件application.yml配置如下(具体配置项作用见注释):
spring:
  application:
    name: spring-boot-examples-admin-client
  boot:
    admin:
      client:
        url: "http://localhost:8090/" #spring admin server访问地址
        username: admin #spring admin server用户名
        password: 123456 #spring admin server密码
        instance:
          metadata:
            user.name: ${spring.security.user.name} #客户端元数据访问用户
            user.password: ${spring.boot.admin.client.password} #客户端元数据访问密码
  security:
    user:
      name: client #客户端用户名
      password: 123456 # 客户端密码
      roles: ACTUATOR_ADMIN #拥有角色,用于允许自身访问

# 开放所有endpoint,实际生产根据自身需要开放,出于安全考虑不建议全部开放。
management:
  endpoints:
    web:
      exposure:
        include: "*"

logging:
  path: logs/
  file: admin-client

server:
  port: 8091

启动演示

  • 分别启动spring-boot-examples-admin-server和spring-boot-examples-admin-client。

  • 访问http://localhost:8090,可看到登录页面。 登录页面

  • 登录成功后,application页面。 application

  • Wallboard页面。 image.png

  • 应用监控详情页面 wallboard01wallboard02

参考源码

码云:https://gitee.com/centy/spring-boot-examples

尾巴

Spring Boot Admin使用在Spring Cloud中使用时,可以与Eureka结合在一起使用,Spring Boot Admin可以通过Eureka发现其它注册到Eureka中的服务。

转载于:https://my.oschina.net/centychen/blog/3009793

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值