SpringBoot整合Spring?Boot?Admin實現(xiàn)服務監(jiān)控的方法
Spring Boot Admin用于管理和監(jiān)控一個或多個Spring Boot服務,其分為Server端和Client端,Server端相當于一個注冊中心,Client端通過Http請求向Server端進行注冊,也可以結合Eureka、Nacos等注冊中心實現(xiàn)服務注冊。
1. Server端服務開發(fā)
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端服務開發(fā)
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(---){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,登陸成功后,可以看到如下頁面
點擊該服務可以進入具體的監(jiān)控頁面,注意需要點擊下圖箭頭所指位置
點擊進入服務后,可以看到如下信息
將滾動條往下拉,可以看到內存、線程等信息
選擇日志—>日志文件可以查看到服務的日志信息
點擊日志配置可以動態(tài)調節(jié)每個包/類的日志級別
選擇應用墻選項,可以查看到應用有哪些服務被監(jiān)控
4. 配置郵件告警
Spring Boot Admin還可以對其監(jiān)控的服務提供告警功能,當出現(xiàn)重大故障,如服務宕機時,可以及時以郵件方式通知運維人員
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: 發(fā)件人郵箱
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實現(xiàn)服務監(jiān)控的文章就介紹到這了,更多相關Spring Boot Admin服務監(jiān)控內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java中ByteArrayInputStream和ByteArrayOutputStream用法詳解
這篇文章主要介紹了Java中ByteArrayInputStream和ByteArrayOutputStream用法詳解,?ByteArrayInputStream?的內部額外的定義了一個計數器,它被用來跟蹤?read()?方法要讀取的下一個字節(jié)2022-06-06springboot如何通過session實現(xiàn)單點登入詳解
單點登錄(SSO)的定義是在多個應用系統(tǒng)中,用戶只需要登錄一次就可以訪問所有相互信任的應用系統(tǒng),下面這篇文章主要給大家介紹了關于springboot如何通過session實現(xiàn)單點登入的相關資料,需要的朋友可以參考下2021-12-12IDEA不識別Java文件:文件變橙色&顯示后綴名.java的解決
這篇文章主要介紹了IDEA不識別Java文件:文件變橙色&顯示后綴名.java的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03