您当前的位置: 首页 >  spring boot

蔚1

暂无认证

  • 0浏览

    0关注

    4753博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Spring Boot Admin 2.0 详解

蔚1 发布时间:2020-04-14 23:30:54 ,浏览量:0

Spring Boot Admin 是一个开源社区项目,用于管理和监控 Spring Boot 应用程序。 应用程序作为 Spring Boot Admin Client 向为 Spring Boot Admin Server 注册(通过 HTTP)或使用 Spring Cloud 注册中心(例如 Eureka、Consul)发现。 UI 是的 Vue.js 应用程序,展示S pring Boot Admin Client 的 Actuator 端点上的一些监控。服务端采用 Spring WebFlux + Netty 的方式。

一、什么是 Spring Boot Admin ?

Spring Boot Admin 是一个开源社区项目,用于管理和监控 SpringBoot 应用程序。 应用程序作为 Spring Boot Admin Client 向为 Spring Boot Admin Server 注册(通过 HTTP)或使用 SpringCloud 注册中心(例如 Eureka,Consul)发现。 UI 是的 Vue.js 应用程序,展示 Spring Boot Admin Client 的 Actuator 端点上的一些监控。服务端采用 Spring WebFlux + Netty 的方式。Spring Boot Admin 为注册的应用程序提供以下功能:

  • 显示健康状况
  • 显示详细信息,例如
  • JVM 和内存指标
  • micrometer.io 指标
  • 数据源指标
  • 缓存指标
  • 显示构建信息编号
  • 关注并下载日志文件
  • 查看 jvm system-和 environment-properties
  • 查看 Spring Boot 配置属性
  • 支持 Spring Cloud 的 postable / env-和/ refresh-endpoint
  • 轻松的日志级管理
  • 与 JMX-beans 交互
  • 查看线程转储
  • 查看 http-traces
  • 查看 auditevents
  • 查看 http-endpoints
  • 查看计划任务
  • 查看和删除活动会话(使用 spring-session)
  • 查看 Flyway / Liquibase 数据库迁移
  • 下载 heapdump
  • 状态变更通知(通过电子邮件,Slack,Hipchat,……)
  • 状态更改的事件日志(非持久性)
二、入门 1. 创建 Spring Boot Admin Server pom.xml
    4.0.0            org.springframework.boot        spring-boot-starter-parent        2.1.0.RELEASE                 com.gf    admin-server    0.0.1-SNAPSHOT    admin-server    Demo project for Spring Boot            1.8        2.1.0                            org.springframework.boot            spring-boot-starter-web                            de.codecentric            spring-boot-admin-starter-server                            org.springframework.boot            spring-boot-starter-test            test                                                    de.codecentric                spring-boot-admin-dependencies                ${spring-boot-admin.version}                pom                import                                                                org.springframework.boot                spring-boot-maven-plugin                        
application.yml
spring:  application:    name: admin-serverserver:  port: 8769
启动类 AdminServerApplication

启动类加上@EnableAdminServer 注解,开启 AdminServer 的功能:

@SpringBootApplication@EnableAdminServerpublic class AdminServerApplication {    public static void main(String[] args) {        SpringApplication.run( AdminServerApplication.class, args );    }}
2. 创建 Spring Boot Admin Client pom.xml
    4.0.0            org.springframework.boot        spring-boot-starter-parent        2.1.0.RELEASE                 com.gf    admin-client    0.0.1-SNAPSHOT    admin-client    Demo project for Spring Boot            1.8        2.1.0                            org.springframework.boot            spring-boot-starter-web                            de.codecentric            spring-boot-admin-starter-client                            org.springframework.boot            spring-boot-starter-test            test                                                    de.codecentric                spring-boot-admin-dependencies                ${spring-boot-admin.version}                pom                import                                                                org.springframework.boot                spring-boot-maven-plugin                        
application.yml
  • spring.boot.admin.client.url:要注册的 Spring Boot Admin Server 的 URL。
  • management.endpoints.web.exposure.include:与 Spring Boot 2 一样,默认情况下,大多数 actuator 的端口都不会通过 http 公开,* 代表公开所有这些端点。对于生产环境,应该仔细选择要公开的端点。
spring:  application:    name: admin-client  boot:    admin:      client:        url: http://localhost:8769server:  port: 8768management:  endpoints:    web:      exposure:        include: '*'  endpoint:    health:      show-details: ALWAYS
启动类 AdminClientApplication
@SpringBootApplicationpublic class AdminClientApplication {    public static void main(String[] args) {        SpringApplication.run( AdminClientApplication.class, args );    }}

启动两个工程,在浏览器上输入 localhost:8769 ,浏览器显示的界面如下:

查看 wallboard:

点击 wallboard,可以查看 admin-client 具体的信息,比如内存状态信息:

查看 spring bean 的情况:

查看应用程序运行状况,信息和详细:

还有很多监控信息,多点一点就知道。

三、集成 Eureka 1. 创建 sc-eureka-server

这是一个 eureka-server 注册中心。

pom.xml
    4.0.0            org.springframework.boot        spring-boot-starter-parent        2.1.0.RELEASE                 com.gf    sc-admin-server    0.0.1-SNAPSHOT    sc-admin-server    Demo project for Spring Boot            1.8        2.1.0        Finchley.RELEASE                            org.springframework.boot            spring-boot-starter-web                            de.codecentric            spring-boot-admin-starter-server            2.1.0                            org.springframework.cloud            spring-cloud-starter-netflix-eureka-client                            org.springframework.boot            spring-boot-starter-test            test                            org.springframework.boot            spring-boot-starter-security                            org.springframework.boot            spring-boot-starter-mail                            org.jolokia            jolokia-core                                                    org.springframework.cloud                spring-cloud-dependencies                ${spring-cloud.version}                pom                import                                        de.codecentric                spring-boot-admin-dependencies                ${spring-boot-admin.version}                pom                import                                                                org.springframework.boot                spring-boot-maven-plugin                        
application.yml
spring:  application:    name: sc-eureka-serverserver:  port: 8761eureka:  client:    service-url:      defaultZone: http://localhost:8761/eureka    register-with-eureka: false    fetch-registry: falsemanagement:  endpoints:    web:      exposure:        include: "*"  endpoint:    health:      show-details: ALWAYS
启动类 ScEurekaServerApplication
@SpringBootApplication@EnableEurekaServerpublic class ScEurekaServerApplication {    public static void main(String[] args) {        SpringApplication.run( ScEurekaServerApplication.class, args );    }}
2. 创建 sc-admin-server

这是一个 Spring Boot Admin Server 端。

pom.xml
    4.0.0            org.springframework.boot        spring-boot-starter-parent        2.1.0.RELEASE                 com.gf    sc-admin-server    0.0.1-SNAPSHOT    sc-admin-server    Demo project for Spring Boot            1.8        2.1.0        Finchley.RELEASE                            org.springframework.boot            spring-boot-starter-web                            de.codecentric            spring-boot-admin-starter-server            2.1.0                            org.springframework.cloud            spring-cloud-starter-netflix-eureka-client                            org.springframework.boot            spring-boot-starter-test            test                            org.springframework.boot            spring-boot-starter-security                            org.springframework.boot            spring-boot-starter-mail                            org.jolokia            jolokia-core                                                    org.springframework.cloud                spring-cloud-dependencies                ${spring-cloud.version}                pom                import                                        de.codecentric                spring-boot-admin-dependencies                ${spring-boot-admin.version}                pom                import                                                                org.springframework.boot                spring-boot-maven-plugin                        
application.yml
spring:  application:    name: admin-serverserver:  port: 8769eureka:  client:    registryFetchIntervalSeconds: 5    service-url:      defaultZone: ${EUREKA_SERVICE_URL:http://localhost:8761}/eureka/  instance:    leaseRenewalIntervalInSeconds: 10    health-check-url-path: /actuator/healthmanagement:  endpoints:    web:      exposure:        include: "*"  endpoint:    health:      show-details: ALWAYS
启动类 ScAdminServerApplication
@SpringBootApplication@EnableAdminServer@EnableDiscoveryClientpublic class ScAdminServerApplication {    public static void main(String[] args) {        SpringApplication.run( ScAdminServerApplication.class, args );    }}
3. 创建 sc-admin-client

这是一个 Spring Boot Admin client 端。

pom.xml
    4.0.0            org.springframework.boot        spring-boot-starter-parent        2.1.0.RELEASE                 com.gf    sc-admin-client    0.0.1-SNAPSHOT    sc-admin-client    Demo project for Spring Boot            1.8        2.1.0        Finchley.SR2                            org.springframework.boot            spring-boot-starter-actuator                            org.springframework.boot            spring-boot-starter-web                            org.springframework.boot            spring-boot-starter-webflux                            de.codecentric            spring-boot-admin-starter-client                            org.springframework.cloud            spring-cloud-starter-netflix-eureka-client                            org.springframework.boot            spring-boot-starter-test            test                                                    org.springframework.cloud                spring-cloud-dependencies                ${spring-cloud.version}                pom                import                                        de.codecentric                spring-boot-admin-dependencies                ${spring-boot-admin.version}                pom                import                                                                org.springframework.boot                spring-boot-maven-plugin                        
application.yml
spring:  application:    name: sc-admin-clienteureka:  instance:    leaseRenewalIntervalInSeconds: 10    health-check-url-path: /actuator/health  client:    registryFetchIntervalSeconds: 5    service-url:      defaultZone: ${EUREKA_SERVICE_URL:http://localhost:8761}/eureka/management:  endpoints:    web:      exposure:        include: "*"  endpoint:    health:      show-details: ALWAYSserver:  port: 8762
启动类 ScAdminClientApplication
@SpringBootApplication@EnableDiscoveryClientpublic class ScAdminClientApplication {    public static void main(String[] args) {        SpringApplication.run( ScAdminClientApplication.class, args );    }}

启动三个工程,访问 localhost:8769,出现如下界面:

admin 会自己拉取 Eureka 上注册的 app 信息,主动去注册。这也是唯一区别之前入门中手动注册的地方,就是 client 端不需要 admin-client 的依赖,也不需要配置 admin 地址了,一切全部由 admin-server 自己实现。这样的设计对环境变化很友好,不用改了 admin-server 后去改所有 app 的配置了。

四、集成 Spring Security

Web 应用程序中的身份验证和授权有多种方法,因此 Spring Boot Admin 不提供默认方法。默认情况下,spring-boot-admin-server-ui 提供登录页面和注销按钮。我们结合 Spring Security 实现需要用户名和密码登录的安全认证。

sc-admin-server 工程的 pom 文件需要增加以下的依赖:

    org.springframework.boot    spring-boot-starter-security

在 sc-admin-server 工的配置文件 application.yml 中配置 spring security 的用户名和密码,这时需要在服务注册时带上 metadata-map 的信息,如下:

spring:  security:    user:      name: "admin"      password: "admin"eureka:  instance:    metadata-map:      user.name: ${spring.security.user.name}      user.password: ${spring.security.user.password}

@EnableWebSecurity注解以及WebSecurityConfigurerAdapter一起配合提供基于 web 的 security。继承了 WebSecurityConfigurerAdapter 之后,再加上几行代码,我们就能实现要求用户在进入应用的任何 URL 之前都进行验证的功能,写一个配置类 SecuritySecureConfig 继承 WebSecurityConfigurerAdapter,配置如下:

@Configurationpublic class SecuritySecureConfig extends WebSecurityConfigurerAdapter {    private final String adminContextPath;    public SecuritySecureConfig(AdminServerProperties adminServerProperties) {        this.adminContextPath = adminServerProperties.getContextPath();    }    @Override    protected void configure(HttpSecurity http) throws Exception {        // @formatter:off        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();        successHandler.setTargetUrlParameter("redirectTo");        successHandler.setDefaultTargetUrl(adminContextPath + "/");        http.authorizeRequests()                //授予对所有静态资产和登录页面的公共访问权限。                .antMatchers(adminContextPath + "/assets/**").permitAll()                .antMatchers(adminContextPath + "/login").permitAll()                //必须对每个其他请求进行身份验证                .anyRequest().authenticated()                .and()                //配置登录和注销                .formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()                .logout().logoutUrl(adminContextPath + "/logout").and()                //启用 HTTP-Basic 支持。这是 Spring Boot Admin Client 注册所必需的                .httpBasic().and();        // @formatter:on    }}

重新访问 http://localhost:8769/ 会出现登录界面,密码是 配置文件中配置好的,账号 admin 密码 admin,界面如下:

五、通知 1. 邮件通知

在 Spring Boot Admin 中 当注册的应用程序状态更改为 DOWN、UNKNOWN、OFFLINE 都可以指定触发通知,下面讲解配置邮件通知。

在 sc-admin-server 工程 pom 文件,加上 mail 的依赖,如下:

    org.springframework.boot    spring-boot-starter-mail

在配置文件 application.yml 文件中,配置收发邮件的配置:

spring:  mail:    host: smtp.163.com    username: xxxx@163.com    password: xxxx    properties:      mail:        smtp:          auth: true          starttls:            enable: true            required: true  boot:    admin:      notify:        mail:          from: xxxx@163.com          to: xxxx@qq.com

配置后,重启 sc-admin-server 工程,之后若出现注册的客户端的状态从 UP 变为 OFFLINE 或其他状态,服务端就会自动将电子邮件发送到上面配置的收件地址。

注意 : 配置了邮件通知后,会出现 反复通知 service offline / up。这个问题的原因在于 查询应用程序的状态和信息超时,下面给出两种解决方案:

#方法一:增加超时时间(单位:ms)spring.boot.admin.monitor.read-timeout=20000#方法二:关闭闭未使用或不重要的检查点management.health.db.enabled=falsemanagement.health.mail.enabled=falsemanagement.health.redis.enabled=falsemanagement.health.mongo.enabled=false
2. 自定义通知

可以通过添加实现 Notifier 接口的 Spring Beans 来添加您自己的通知程序,最好通过扩展 AbstractEventNotifier 或 AbstractStatusChangeNotifier。在 sc-admin-server 工程中编写一个自定义的通知器:

@Componentpublic class CustomNotifier  extends AbstractStatusChangeNotifier {    private static final Logger LOGGER = LoggerFactory.getLogger( LoggingNotifier.class);    public CustomNotifier(InstanceRepository repository) {        super(repository);    }    @Override    protected Mono doNotify(InstanceEvent event, Instance instance) {        return Mono.fromRunnable(() -> {            if (event instanceof InstanceStatusChangedEvent) {                LOGGER.info("Instance {} ({}) is {}", instance.getRegistration().getName(), event.getInstance(),                        ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus());                String status = ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus();                switch (status) {                    // 健康检查没通过                    case "DOWN":                        System.out.println("发送 健康检查没通过 的通知!");                        break;                    // 服务离线                    case "OFFLINE":                        System.out.println("发送 服务离线 的通知!");                        break;                    //服务上线                    case "UP":                        System.out.println("发送 服务上线 的通知!");                        break;                    // 服务未知异常                    case "UNKNOWN":                        System.out.println("发送 服务未知异常 的通知!");                        break;                    default:                        break;                }            } else {                LOGGER.info("Instance {} ({}) {}", instance.getRegistration().getName(), event.getInstance(),                        event.getType());            }        });    }}

源码下载:https://github.com/gf-huanchupk/SpringBootLearning

阅读全文: http://gitbook.cn/gitchat/activity/5e9521788579b3688e9409fe

您还可以下载 CSDN 旗下精品原创内容社区 GitChat App ,阅读更多 GitChat 专享技术内容哦。

FtooAtPSkEJwnW-9xkCLqSTRpBKX

关注
打赏
1560489824
查看更多评论
立即登录/注册

微信扫码登录

0.0990s