Spring boot admin 服务监控利器详解


Posted in Java/Android onAugust 05, 2022

一、简介

用于对 Spring Boot 应用的管理和监控。可以用来监控服务是否健康、是否在线、以及一些jvm数据等等。
Spring Boot Admin 分为服务端(spring-boot-admin-server)和客户端(spring-boot-admin-client),服务端和客户端之间采用 http 通讯方式实现数据交互;单体项目中需要整合 spring-boot-admin-client 才能让应用被监控。
在 SpringCloud 项目中,spring-boot-admin-server 是直接从注册中心抓取应用信息,不需要每个微服务应用整合 spring-boot-admin-client 就可以实现应用的管理和监控。

Spring boot admin 服务监控利器详解

主要的功能点有:

  • 显示应用程序的监控状态
  • 应用程序上下线监控
  • 查看 JVM,线程信息
  • 可视化的查看日志以及下载日志文件
  • 动态切换日志级别
  • Http 请求信息跟踪

二、搭建

1、服务端

需先搭建服务端,监控服务,被监控的服务连接过来即可,开箱即用。

1、新建一个项目做为服务端
2、引入spring-boot-admin服务端依赖

<!--用于检查系统的监控情况-->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-actuator</artifactId>
 </dependency>
  <!--Spring Boot Admin Server监控服务端-->
 <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>

3、启动类上开启admin@EnableAdminServer

Spring boot admin 服务监控利器详解

4、security安全防护配置

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;
@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/**"
                );
    }
}

5、yml配置

server:
  port: 9111
spring:
  boot:
    admin:
      ui:
        title: HMB服务监控中心
      client:
        instance:
          metadata:
            tags:
              environment: local
         #要获取的client的端点信息
      probed-endpoints: health,env,metrics,httptrace:trace,threaddump:dump,jolokia,info,logfile,refresh,flyway,liquibase,heapdump,loggers,auditevents
      monitor: # 监控发送请求的超时时间
        default-timeout: 20000
  security: # 设置账号密码
    user:
      name: admin
      password: admin
# 服务端点详细监控信息
management:   
  trace:
    http:
      enabled: true
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: always

6、启动项目

访问 http://ip:端口,

如我的http://localhost:9111,账号密码都是admin(上面的security配的)

Spring boot admin 服务监控利器详解

Spring boot admin 服务监控利器详解

7、自定义服务状态变化后,提醒功能

import de.codecentric.boot.admin.server.domain.entities.Instance;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.domain.events.InstanceEvent;
import de.codecentric.boot.admin.server.notify.AbstractStatusChangeNotifier;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Component
public class WarnNotifier extends AbstractStatusChangeNotifier {
	public WarnNotifier(InstanceRepository repository) {
		super(repository);
	}

	@Override
	protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
		// 服务名
		String serviceName = instance.getRegistration().getName();
		// 服务url
		String serviceUrl = instance.getRegistration().getServiceUrl();
		// 服务状态
		String status = instance.getStatusInfo().getStatus();
		// 详情
		Map<String, Object> details = instance.getStatusInfo().getDetails();
		// 当前服务掉线时间
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String format = simpleDateFormat.format(date);
		// 拼接短信内容
		StringBuilder str = new StringBuilder();
		str.append("服务名:【" + serviceName + "】 \r\n");
		str.append("服务状态:【"+ status +"】 \r\n");
		str.append("地址:【" + serviceUrl + "】\r\n");
		str.append("时间:" + format +"\r\n");

		return Mono.fromRunnable(()->{
			// 这里写你服务发生改变时,要提醒的方法
			// 如服务掉线了,就发送短信告知
		});
	}
}

8、服务端配置

配置 默认参数 解释
spring.boot.admin.context-path / server端的访问路径
spring.boot.admin.monitor.status-interval 10,000ms 检查实例状态的时间间隔。

Spring boot admin 服务监控利器详解

Spring boot admin 服务监控利器详解

Spring boot admin 服务监控利器详解

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-actuator</artifactId>
 </dependency>

2、yml配置

server:
  port: 9222
spring:
  application:
    name: client
  boot:
    admin:
      client: # spring-boot-admin 客户端配置
        url: http://localhost:9111 #服务端连接地址
        username: admin # 服务端账号
        password: admin # 服务端密码
        instance:
          prefer-ip: true # 使用ip注册

# 服务端点详细监控信息
management:
  trace:
    http:
      enabled: true
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: always
    logfile: # 日志(想在线看日志才配)
      external-file: ./logs/client-info.log # 日志所在路径

3、启动项目

此时客户端就已经注册进来了。

Spring boot admin 服务监控利器详解

点击可查看更多信息:

Spring boot admin 服务监控利器详解

点击日志也可在线查看日志:

Spring boot admin 服务监控利器详解

此时,如果我们服务掉线了,就会触发服务端的预警功能,告知我们。

4、客户端配置

Spring boot admin 服务监控利器详解

Spring boot admin 服务监控利器详解

3、微服务

除特别说明外,都是在上面的基础上添加

3.1、服务端

1、添加依赖

<!--  nacos注册中心配置-->
  <dependency>
      <groupId>com.alibaba.cloud</groupId>
      <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
      <version>2.2.5.RELEASE</version>
  </dependency>

2、yml添加配置

spring:
  cloud: 
    nacos: 
      discovery:
        server-addr: localhost:8848
#        namespace: # 要和你的服务同一命名空间

3.2、客户端

客户端不用引spring-boot-admin-starter-clien依赖,springbootadmin会去服务列表里找

如果服务有配置context-path路径,则需添加yml配置

spring:
  cloud:
    nacos:
      discovery:
        metadata:  # minitor监控的context-path配置
          management:
            context-path: ${server.servlet.context-path}/actuator

4、我的微服务预警发送其他服务状态信息思路

问题:由于该组件重写状态发生变化时的接口,没有提供其他服务的状态信息,只有本服务,但是如果是集群、多实例,我又想知道,该服务其他实例或者其他的服务状态信息,是否存活。

结果展示:如我的预警内容,发送当前服务状态、当前服务剩余健康实例、其他健康服务数等等

Spring boot admin 服务监控利器详解

到此这篇关于Spring boot admin 服务监控利器详解的文章就介绍到这了,更多相关Spring boot admin 内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Java/Android 相关文章推荐
SpringCloud Alibaba 基本开发框架搭建过程
Jun 13 Java/Android
Java数组与堆栈相关知识总结
Jun 29 Java/Android
Java中CyclicBarrier和CountDownLatch的用法与区别
Aug 23 Java/Android
Java SSM配置文件案例详解
Aug 30 Java/Android
详解Java七大阻塞队列之SynchronousQueue
Sep 04 Java/Android
springboot如何接收application/x-www-form-urlencoded类型的请求
Nov 02 Java/Android
Java异常处理try catch的基本用法
Dec 06 Java/Android
Android基于Fresco实现圆角和圆形图片
Apr 01 Java/Android
Spring Boot 底层原理基础深度解析
Apr 03 Java/Android
SpringBoot整合Minio文件存储
Apr 03 Java/Android
Jmerte 分布式压测及分布式压测配置
Apr 30 Java/Android
一文搞懂Java中的注解和反射
Jun 21 Java/Android
volatile保证可见性及重排序方法
Aug 05 #Java/Android
app场景下uniapp的扫码记录
Jul 23 #Java/Android
IDEA中sout快捷键无效问题的解决方法
Jul 23 #Java/Android
Spring Boot 的创建和运行示例代码详解
阿里面试Nacos配置中心交互模型是push还是pull原理解析
Jul 23 #Java/Android
java实现web实时消息推送的七种方案
前端与RabbitMQ实时消息推送未读消息小红点实现示例
You might like
德劲1104的电路分析与改良
2021/03/01 无线电
两个php日期控制类实例
2014/12/09 PHP
PHP中key和current,next的联合运用实例分析
2016/03/29 PHP
php metaphone()函数及php localeconv() 函数实例解析
2016/05/15 PHP
CodeIgniter集成smarty的方法详解
2016/05/26 PHP
PHP中in_array函数使用的问题与解决办法
2016/09/11 PHP
JavaScript类和继承 prototype属性
2010/09/03 Javascript
jquery中EasyUI使用技巧小结
2015/02/10 Javascript
javascript实现图片上传前台页面
2015/08/18 Javascript
jquery自定义右键菜单、全选、不连续选择
2016/03/01 Javascript
vue2.x 父组件监听子组件事件并传回信息的方法
2017/07/17 Javascript
vue router demo详解
2017/10/13 Javascript
详解Vue-Router源码分析路由实现原理
2019/05/15 Javascript
基于vue实现简易打地鼠游戏
2020/08/21 Javascript
进一步探究Python的装饰器的运用
2015/05/05 Python
python实现二分查找算法
2017/09/21 Python
python添加模块搜索路径和包的导入方法
2019/01/19 Python
24式加速你的Python(小结)
2019/06/13 Python
树莓派用python中的OpenCV输出USB摄像头画面
2019/06/22 Python
Python中生成一个指定长度的随机字符串实现示例
2019/11/06 Python
pycharm运行scrapy过程图解
2019/11/22 Python
pytorch 常用线性函数详解
2020/01/15 Python
Python3自动生成MySQL数据字典的markdown文本的实现
2020/05/07 Python
基于TensorFlow的CNN实现Mnist手写数字识别
2020/06/17 Python
css3 pointer-events 介绍详解
2017/09/18 HTML / CSS
澳大利亚家具和家居用品购物网站:Zanui
2018/12/29 全球购物
丝芙兰墨西哥官网:Sephora墨西哥
2020/05/30 全球购物
请解释一下webService? 如何用.net实现webService
2014/06/09 面试题
后勤园长自我鉴定
2013/10/17 职场文书
新闻记者个人求职的自我评价
2013/11/28 职场文书
新年主持词
2014/03/27 职场文书
某某同志考察材料
2014/05/28 职场文书
家具商场的活动方案
2014/08/16 职场文书
2015年元旦主持词开场白
2014/12/14 职场文书
优秀教师先进材料
2014/12/16 职场文书
小学教师个人总结
2015/02/05 职场文书