環境:SpringBoot2.3.9.RELEASE + SpringBootAdmin2.3.1
說明:如果使用SpringBootAdmin2.4.*版本那么SpringBoot的版本也必須是2.4.*否則啟動報錯。
Spring Boot Admin(SBA)是一個管理和監視SpringBoot應用程序的社區項目。通過Spring Boot Admin Client(通過HTTP)注冊我們的應用程序到Admin Server中,或者使用Spring Cloud®服務發現(例如Eureka、Consul)。
★ 配置Spring Boot Admin服務端
- 添加依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
- 啟動類添加注解
啟動類添加@EnableAdminServer注解
@SpringBootApplication
@EnableAdminServer
public class SpringBootAdminApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootAdminApplication.class, args);
}
}
- 應用配置文件
server:
port: 8080
---
spring:
application:
name: admin-server
---
spring:
boot:
admin:
context-path: /sba
非常簡單,啟動服務直接訪問:http://localhost:8080/sba

空空如也,現在我們還沒有客戶端注冊上來,接下來寫個客戶端。
★ 客戶端注冊
- 添加依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
- 安全配置
放行所有的請求
@Configuration
public class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll()
.and().csrf().disable();
}
}
- 應用配置文件
server:
port: 8081
---
spring:
application:
name: admin-client
---
spring:
boot:
admin:
client:
url:
- http://localhost:8080/sba
啟動客戶端(確保服務端已經啟動)

客戶端已經注冊上來了,但是這里顯示的地址是主機名,修改配置顯示ip地址
- 顯示客戶端IP
spring:
boot:
admin:
client:
url:
- http://localhost:8080
instance:
prefer-ip: true

點擊實例進入查看實例的詳細信息

- 查看日志
應用中配置日志功能,在應用配置文件中配置logging.file.path or logging.file.name兩個只能配置一個
logging:
file:
path: d:/logs
pattern:
file: '%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID}){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx'
這樣配置完后重啟,在實例的詳細頁面中就能查看日志信息了

- 保護Server端,添加登錄功能
加入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
安全配置
@Configuration(proxyBeanMethods = false)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final AdminServerProperties adminServer;
private final SecurityProperties security;
public SecurityConfig(AdminServerProperties adminServer, SecurityProperties security) {
this.adminServer = adminServer;
this.security = security;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(this.adminServer.path("/"));
http.authorizeRequests((authorizeRequests) -> authorizeRequests.antMatchers(this.adminServer.path("/assets/**"))
.permitAll().antMatchers(this.adminServer.path("/actuator/info")).permitAll()
.antMatchers(this.adminServer.path("/actuator/health")).permitAll()
.antMatchers(this.adminServer.path("/login")).permitAll().anyRequest().authenticated())
.formLogin((formLogin) -> formLogin.loginPage(this.adminServer.path("/login"))
.successHandler(successHandler).and())
.logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout")))
.httpBasic(Customizer.withDefaults())
.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(
new AntPathRequestMatcher(this.adminServer.path("/instances"),
HttpMethod.POST.toString()),
new AntPathRequestMatcher(this.adminServer.path("/instances/*"),
HttpMethod.DELETE.toString()),
new AntPathRequestMatcher(this.adminServer.path("/actuator/**"))))
.rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600));
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser(security.getUser().getName())
.password("{noop}" + security.getUser().getPassword()).roles("USER");
}
}
應用配置文件
spring:
boot:
admin:
context-path: /sba
security:
user:
name: admin
password: admin
配置用戶和密碼
再次啟動服務

再次啟動客戶端,有如下錯誤

修改客戶端配置,需要配置admin server的認證信息
spring:
boot:
admin:
client:
username: admin
password: admin
url:
- http://localhost:8080/sba
instance:
prefer-ip: true
添加
spring.boot.admin.client.username和spring.boot.admin.client.password用戶名密碼
再次啟動注冊成功

admin server是通過actuator來實時監控系統的,那如果客戶端的設置了認證信息呢?會發生什么情況?
- 保護Client端認證信息
客戶端加入security
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
配置認證信息
spring:
security:
user:
name: ak
password: 123456
啟動客戶端

客戶端是注冊上來了,但是信息很少。修改客戶端配置信息
spring:
boot:
admin:
client:
username: admin
password: admin
url:
- http://localhost:8080/sba
instance:
prefer-ip: true
metadata:
user.name: ${spring.security.user.name}
user.password: ${spring.security.user.password}
---
spring:
security:
user:
name: ak
password: 123456
注冊的時候配置元信息
再次啟動客戶端

現在完全正常了。
- 動態修改日志級別
定義一個接口,輸出參數信息
@RestController
@RequestMapping("/demo")
public class DemoController {
private static Logger logger = LoggerFactory.getLogger(DemoController.class) ;
@GetMapping("/{id}")
public Object index(@PathVariable("id") String id) {
logger.debug("DEBUG接收到參數: {}", id) ;
logger.info("INFO接收到參數:{}", id) ;
return id ;
}
}
配置文件中加入日志級別
logging:
level:
'[com.pack.controller]': debug
監控端查看日志配置

請求接口查看控制臺輸出

info, debug都輸出了,通過監控端,修改日志級別

再次請求,查看控制臺輸出

現在只有info了。如果服務重啟那么日志會還原的