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
  • 应用监控详情页面


    wallboard01

    wallboard02

参考源码

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

尾巴

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容