spring boot admin 介紹
Spring Boot Admin 是一個管理和監控你的 Spring Boot 應用程序的應用程序。 這些應用程序通過 Spring Boot Admin Client(通過 HTTP)註冊或者使用 Spring Cloud(例如 Eureka)發現。
關於ui界面:Spring Boot Admin ui頁面早期是使用的AngularJs應用;目前使用的是vue應用。
使用方面:Spring Boot Admin 主要是用於監控springboot 項目的狀態、log日誌等功能。同時還可以和微服務結合應用,該篇文章只說單體的spring boot如何集成,廢話不多說下面是集成例子 。
spring boot admin 集成
spring boot admin 有客戶端和服務端之分,客戶端連接服務端之後纔可以在服務端監控客戶端的狀態。
服務端的創建
服務端的創建相對來說比較簡單,我這裏使用mvn構建的工程,首先創建一個spring boot 項目引入如下依賴
(這個項目使用了security權限控制,簡單的應用就不挨個排除了)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 這個是springboot 權限控制的依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
</dependency>
配置文件如下
server:
port: 8185
spring:
security:
user:
name: admin
password:123456
spring security權限配置如下
package com.weichai.timing.admin;
import de.codecentric.boot.admin.server.config.AdminServerProperties;
import io.netty.handler.codec.http.HttpMethod;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import java.util.UUID;
/**
* @ClassName SecuritySecureConfig
* @Description TODO
* @Author youzi
* @Date 2020/3/12 4:32 下午
* @Version 1.0
**/
@Configuration(proxyBeanMethods = false)
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
private final AdminServerProperties adminServer;
public SecuritySecureConfig(AdminServerProperties adminServer) {
this.adminServer = adminServer;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(this.adminServer.path("/"));
http.authorizeRequests()
.antMatchers(this.adminServer.path("/assets/**")).permitAll()
.antMatchers(this.adminServer.path("/login")).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage(this.adminServer.path("/login")).successHandler(successHandler).and()
.logout().logoutUrl(this.adminServer.path("/logout")).and()
.httpBasic().and()
.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/**"))
)
.and()
.rememberMe().key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600);
}
}
最後需要注意的地方:
首先需要開啓cros跨域請求的設置,這個設置需要打開,在文章最後會進行問題統一的說明。
cors跨域請求配置如下
package com.weichai.timing.admin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @ClassName CorsConfiguration
* @Description 跨域請求處理(允許跨域)
* @Author youzi
* @Date 2020/3/12 1:40 下午
* @Version 1.0
**/
@Configuration
public class CorsConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("*")
.allowedMethods("*")
.allowedOrigins("*");
}
};
}
}
到這裏服務端的配置就完成了,運行項目,然後訪問localhost:8185此時會出現如下界面
登錄之後如下(我這個已經部署了一個服務端因此顯示1正常的話如果沒有服務端則顯示爲0)
客戶端創建
pom文件引入配置如下(客戶端我這裏也集成了spring security)
<!-- spring boot 監控-->
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.2.1</version>
</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>
yml配置文件鏈接服務端如下
spring:
# 設置服務名
application:
name: timing
jmx:
enabled: true
# 設置spring-boot-admin服務端地址
boot:
admin:
client:
# 服務端url
url: http://127.0.0.1:8185
# 服務端用戶名密碼
username: admin
password: 123456
....n多配置....
# 設置spring-boot-admin服務端地址
# 打開客戶端 Actuator 的監控
management:
endpoints:
web:
exposure:
# 開放所有端點
include: "*"
# 關閉redis 健康監視
health:
redis:
enabled: false
security:
user:
name: admin
password: 123456
ip-white: localhost,127.0.0.1
spring-security文件如下:
package com.weichai.timing.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* @ClassName WebSecurityConfig
* @Description TODO
* @Author youzi
* @Date 2020/3/9 7:31 下午
* @Version 1.0
**/
@Configuration
// 註解開啓Spring Security的功能
@EnableWebSecurity
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${spring.security.user.name}")
private String userName;
@Value("${spring.security.user.password}")
private String passWord;
@Value("${spring.security.user.ip-white}")
private String ipWhite;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//設置所有人都可以訪問的頁面
.antMatchers("/druid/**").permitAll()
//設置ip白名單
.antMatchers("/actuator/**").access(createHasIpRangeExpression())
//設置需要登錄的頁面
.antMatchers("/**").hasRole("ADMIN")
//設置所有頁面需要登錄
.anyRequest().authenticated()
.and()
.formLogin()
// .loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.csrf().disable();
// .ignoringAntMatchers("/druid/*")
// .ignoringAntMatchers("/logout");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
//設置加密方式
.passwordEncoder(new BCryptPasswordEncoder())
.withUser(userName)
//加密
.password(new BCryptPasswordEncoder()
.encode(passWord)).roles("ADMIN");
}
private String createHasIpRangeExpression(){
List<String> validIps = Arrays.asList(ipWhite.split("\\s*,\\s*"));
String hasIpRangeAccessExpresion = validIps.stream()
.collect(Collectors.joining("') or hasIpAddress('", "hasIpAddress('","')"));
return hasIpRangeAccessExpresion;
}
}
此時運行服務端就會發現,springbootadmin中有了服務端的監控,截圖在上面已經發過。
注意
接下來會說我再使用過程當中發現的問題:
-
使用過程當中建議服務端開啓cros服務端也開啓吧(這個我沒有實測,也有別的解決方案,需自行測試)
-
服務端spring security登錄設置問題
描述: 當服務端設置登錄,服務端掉客戶端獲取信息的時候,需要權限會導致服務一直註冊失敗。
解決方案:-
方案1:
根據資料網上大多數的都是在yml如下配置client: # 服務端url url: http://127.0.0.1:8185 # 服務端用戶名密碼 username: admin password: 123456 # 客戶端設置(引入安全框架之後如果不放行默認攔截所有) instance: prefer-ip: true service-url: http://localhost:8080 name: timing metadata: # 客戶端賬號密碼告訴服務端 user.name: ${spring.security.user.name} user.password: ${spring.security.user.password}
根據描述說的是這樣就可以服務端調用客戶端的時候就可以通過賬號密碼登錄,但是實測一直登錄不上
備註: 如果客戶端只用spring-security設置賬號密碼然後使用這種方式是可以登錄註冊上,但問題就是java中配置了一些別的東西,我初步懷疑是WebSecurityConfig某些配置影響了,如有大佬知道可以告訴我。- 方案2:
通過設置ip白名單來暴露所需接口
- 方案2:
-
我這裏採用的是方案2的配置,我在安全框架裏面放行了,localhost和127.0.0.1兩個ip,但是實際生產環境這麼搞也是存在安全問題的,暫時未深入的研究,個人覺得登錄的方式應該也可以實現
寫在最後
開源框架也是別研究邊學習,也是引用了別人寫的一些東西,如果有不妥得地方可以直接指出,有問題直接留言就好了