首頁 > 軟體

SpringBoot整合Spring Boot Admin實現服務監控的方法

2022-03-18 19:00:57

Spring Boot Admin用於管理和監控一個或多個Spring Boot服務,其分為Server端和Client端,Server端相當於一個註冊中心,Client端通過Http請求向Server端進行註冊,也可以結合Eureka、Nacos等註冊中心實現服務註冊。

1. Server端服務開發

1.1. 引入核心依賴

<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-server</artifactId>
    <version>2.3.1</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

1.2. application.yml組態檔

server:
  port: 8138
  servlet:
    context-path: /admin
spring:
  application:
    name: springboot-admin-server
  security:
    user:
      name: admin
      password: 123456

1.3. Security組態檔

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private String adminSecurityContextPath;
    public SecurityConfig(AdminServerProperties adminServerProperties) {
        this.adminSecurityContextPath = adminServerProperties.getContextPath();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        http.authorizeRequests()
                .antMatchers(adminSecurityContextPath + "/assets/**").permitAll()
                .antMatchers(adminSecurityContextPath + "/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage(adminSecurityContextPath + "/login").successHandler(successHandler)
                .logout().logoutUrl(adminSecurityContextPath + "/logout")
                .httpBasic()
                .csrf()
                .ignoringAntMatchers(adminSecurityContextPath + "/instances", adminSecurityContextPath + "/actuator/**")
                .disable();
}

1.4. 主啟動類

@EnableAdminServer
@SpringBootApplication
public class AdminServerApplication {

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

2. Client端服務開發

2.1. 引入核心依賴

<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-client</artifactId>
    <version>2.3.1</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.2. application.yml組態檔

server:
  port: 8238
spring:
  application:
    name: springboot-admin-client
  boot:
    admin:
      client:
        url: http://localhost:8138/admin
        instance:
          prefer-ip: true
        username: admin
        password: 123456
management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: always
    shutdown:
      enabled: true
    logfile:
      external-file: ./logs/log_file.log
logging:
  config: classpath:logback-spring.xml
  level:
    com.xlhj.boot.admin: debug
info:
  author: caijliu
  projectName: springboot整合springboot admin
  version: 1.0

2.3. logback-spring.xml檔案

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <property name="log.path" value="./logs"/>
    <!--彩色紀錄檔依賴的渲染類-->
    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter"/>
    <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
    <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />

    <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(-&#45;&#45;){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
    <include resource="org/springframework/boot/logging/logback/file-appender.xml"/>
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>
    <!--設定紀錄檔輸出到檔案-->
    <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}/log_file.log</file>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- 每天紀錄檔歸檔路徑以及格式 -->
            <FileNamePattern>${log.path}/log_file-%d{yyyy-MM-dd}-%i.log</FileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <!--紀錄檔檔案保留天數-->
            <maxHistory>15</maxHistory>
        </rollingPolicy>
    <logger name="com.xlhj.boot.admin" level="info"/>
    <root level="info">
        <appender-ref ref="console"/>
        <appender-ref ref="file"/>
    </root>
</configuration>

2.4. 主啟動類

@SpringBootApplication
public class AdminClientApplication {

    private static Logger logger = LoggerFactory.getLogger(AdminClientApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(AdminClientApplication.class, args);
        logger.info("服務啟動成功,當前時間為:{}", LocalDateTime.now());
        logger.error("服務啟動成功,當前時間為:{}", LocalDateTime.now());
    }
}

3. 驗證

分別啟動Server和Client服務,在瀏覽器輸入地址:http://localhost:8138/admin

輸入使用者名稱和密碼:admin/123456,登陸成功後,可以看到如下頁面

點選該服務可以進入具體的監控頁面,注意需要點選下圖箭頭所指位置

點選進入服務後,可以看到如下資訊

將卷軸往下拉,可以看到記憶體、執行緒等資訊

選擇紀錄檔—>紀錄檔檔案可以檢視到服務的紀錄檔資訊

點選紀錄檔設定可以動態調節每個包/類的紀錄檔級別

選擇應用牆選項,可以檢視到應用有哪些服務被監控

4. 設定郵件告警

Spring Boot Admin還可以對其監控的服務提供告警功能,當出現重大故障,如服務宕機時,可以及時以郵件方式通知運維人員

4.1. 引入核心依賴

在Server服務中引入郵件依賴

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

4.2. application.yml

在yml組態檔中加入如下設定資訊

spring:
  mail:
    host: smtp.qq.com
    username: xxxxx@qq.com
    password: 授權碼
  boot:
    admin:
      notify:
        mail:
          to: 收件人郵箱
          from: 發件人郵箱

4.3. 通知組態檔

@Configuration
public class NotificationConfig {

    private InstanceRepository instanceRepository;
    private ObjectProvider<List<Notifier>> provider;

    public NotificationConfig(InstanceRepository instanceRepository, ObjectProvider<List<Notifier>> provider) {
        this.instanceRepository = instanceRepository;
        this.provider = provider;
    }

    @Bean
    public FilteringNotifier filteringNotifier() {
        CompositeNotifier compositeNotifier = new CompositeNotifier(this.provider.getIfAvailable(Collections::emptyList));
        return new FilteringNotifier(compositeNotifier, this.instanceRepository);
    }

    @Bean
    @Primary
    public RemindingNotifier remindingNotifier() {
        RemindingNotifier remindingNotifier = new RemindingNotifier(filteringNotifier(), this.instanceRepository);
        //設定每隔多久提示
        remindingNotifier.setReminderPeriod(Duration.ofMinutes(1));
        //設定每隔多久檢查
        remindingNotifier.setCheckReminderInverval(Duration.ofSeconds(10));
        return remindingNotifier;
    }
}

4.4. 驗證

先將Client服務關閉,稍等一會便會收到宕機提示郵件

再次將Client服務啟動

到此這篇關於SpringBoot整合Spring Boot Admin實現服務監控的文章就介紹到這了,更多相關Spring Boot Admin服務監控內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com