1. 什么是Spring Boot Admin
gitHub
springboot 有一个非常好用的监控和管理的源软件,这个软件就是spring boot admin,该软件能够将Actuator中的信息进行图形化的展示,也可以监控 Spring Boot 应用的健康状况,提供实时报警功能.
主要的功能点有
- 显示应用程序的监控状态
- 应用程序上下线监控
- 查看JVM,线程信息
- 可视化的查看日志以及下载日志文件
- 动态切换日志级别
- http请求信息跟踪
- 其他功能点...
2. 服务端继承
2.1 设置Spring Boot Admin Server
pom.xml
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
de.codecentric
spring-boot-admin-starter-server
2.3.0
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-actuator
org.springframework.boot
spring-boot-starter-security
设置启动类
/**
* @PROJECT_NAME: 杭州品茗信息技术有限公司
* @DESCRIPTION:
* @author: 徐子木
* @DATE: 2021/1/4 9:24 上午
*/
@EnableAdminServer
@EnableDiscoveryClient
@SpringBootApplication
public class MainBootAdmin {
public static void main(String[] args) {
SpringApplication.run(MainBootAdmin.class,args);
}
}
bootstrap.yml注册到nacos(配置nacos地址,开启actuator全部端点,配置日志打印路径)
spring:
application:
name: boot-admin
cloud:
nacos:
discovery:
server-addr: 192.168.10.37:18848
namespace: 77613cbe-9303-4d79-983e-8e5aef69cc45
group: PM_DEV
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
logging:
file: /home/java/admin.log
2.2 集成Spring security
由于多种方法可以解决分布式Web应用程序中的身份验证和授权,因此SpringBootAdmin不会提供默认方法,默认情况下Spring-boot-admin-server-ui提供了登录页面和注销功能
添加配置
cloud:
nacos:
discovery:
server-addr: 192.168.10.37:18848
namespace: 77613cbe-9303-4d79-983e-8e5aef69cc45
group: PM_DEV
metadata:
user.name: "admin"
user.password: "pinming9158"
security:
user:
name: "admin"
password: "pinming9158"
编写Security的配置
package com.zimu.boot.config;
import de.codecentric.boot.admin.server.config.AdminServerProperties;
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;
/**
* @PROJECT_NAME: 杭州品茗信息技术有限公司
* @DESCRIPTION:
* @author: 徐子木
* @DATE: 2021/1/4 4:26 下午
*/
@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","/css/**","/js/**","/image/*").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/**"
);
}
}
启动项目,即可看到登录页面,输入配置的账号密码登录,能看到注册的服务
页面还是挺好看的
2.3 跨域影响
由于Spring Admin Server UI 里有很多js和css,在我们上生产时,大多数选择nginx代理加重定向头的组合,这会是页面加载崩溃,找不到元素,所以我们要配置nginx代理的proxy_set_header 以及服务端跨域处理
location ^~ /control/ {
proxy_pass http://192.168.10.37:7979;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto https;
}
package com.zimu.boot.config;
import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.apache.catalina.valves.RemoteIpValve;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
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.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* @PROJECT_NAME: 杭州品茗信息技术有限公司
* @DESCRIPTION:
* @author: 徐子木
* @DATE: 2021/1/4 4:30 下午
*/
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")
.allowedHeaders("origin", "content-type", "accept", "x-requested-with")
.maxAge(3600);
}
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
List list = new ArrayList<>();
list.add("*");
corsConfiguration.setAllowedOrigins(list);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
@Bean
public TomcatServletWebServerFactory servletContainer(){
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory ();
factory.setUriEncoding(Charset.forName("UTF-8"));
RemoteIpValve value = new RemoteIpValve();
value.setRemoteIpHeader("X-Forwarded-For");
value.setProtocolHeader("X-Forwarded-Proto");
value.setProtocolHeaderHttpsValue("https");
factory.addEngineValves(value);
return factory;
}
}
2.4 报警邮件
在我们服务宕机或上线时可以自动触发邮件发送,需要提前开启邮件的imtp和smtp功能,请自行了解
pom.xml
org.springframework.boot
spring-boot-starter-mail
配置账号
boot:
admin:
context-path: "control"
notify:
mail:
to: [email protected] # 发送给
from: [email protected] #发送者
mail:
default-encoding: UTF-8
host: #邮件服务器
username: ##用户名
password: #密码
properties:
mail:
debug: false
smtp:
port: 465
auth: true
ssl:
enable: true
socket-factory: sf
手动停止一个服务看下效果,成功发送报警邮件
3. 客户端注册
pom.xml
de.codecentric
spring-boot-admin-starter-client
2.3.0
org.springframework.boot
spring-boot-starter-actuator
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
启动类
client端相对简单,因为nacos自动帮我们整合了与admin的关联工作,只需要注册进nacos,并且与服务端保持在同一命名空间和分组下即可
bootstrap.yml
cloud:
nacos:
discovery:
server-addr: 192.168.10.37:18848
namespace: 77613cbe-9303-4d79-983e-8e5aef69cc45
group: PM_DEV
metadata:
management:
management:
health:
redis:
enabled: false
sentinel:
enabled: false
ldap:
enabled: false
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: always
logging:
file:
一切就绪就可以在控制台看到我们的服务了