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 相关文章推荐
浅谈Java实现分布式事务的三种方案
Jun 11 Java/Android
Java输出Hello World完美过程解析
Jun 13 Java/Android
gateway网关接口请求的校验方式
Jul 15 Java/Android
Log4j.properties配置及其使用
Aug 02 Java/Android
SpringBoot整合RabbitMQ的5种模式实战
Aug 02 Java/Android
详解Spring Security中的HttpBasic登录验证模式
Mar 17 Java/Android
springboot+zookeeper实现分布式锁
Mar 21 Java/Android
Java 超详细讲解数据结构中的堆的应用
Apr 02 Java/Android
Dubbo+zookeeper搭配分布式服务的过程详解
Apr 03 Java/Android
Java Lambda表达式常用的函数式接口
Apr 07 Java/Android
Java实现字符串转为驼峰格式的方法详解
Jul 07 Java/Android
JDK8中String的intern()方法实例详细解读
Sep 23 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
咖啡豆要不要放冰箱的原因
2021/03/04 冲泡冲煮
实战mysql导出中文乱码及phpmyadmin导入中文乱码的解决方法
2010/06/11 PHP
PHP中simplexml_load_string函数使用说明
2011/01/01 PHP
php将html转成wml的WAP标记语言实例
2015/07/08 PHP
php中strlen和mb_strlen用法实例分析
2016/11/12 PHP
使两个iframe的高度与内容自适应,且相等
2006/11/20 Javascript
JavaScript RegExp方法获取地址栏参数(面向对象)
2009/03/10 Javascript
extJs 下拉框联动实现代码
2010/04/09 Javascript
JS操作图片(增,删,改) 例子
2013/04/17 Javascript
一个Action如何调用两个不同的方法
2014/05/22 Javascript
nodejs实现获取某宝商品分类
2015/05/28 NodeJs
JavaScript中rem布局在react中的应用
2015/12/09 Javascript
Bootstrap对话框使用实例讲解
2016/09/24 Javascript
js监听键盘事件的方法_原生和jquery的区别详解
2016/10/10 Javascript
JQuery ZTree使用方法详解
2017/01/07 Javascript
angular分页指令操作
2017/01/09 Javascript
jquery实现折叠菜单效果【推荐】
2017/03/08 Javascript
解决BootStrap Fileinput手机图片上传显示旋转问题
2017/06/01 Javascript
前后端常见的几种鉴权方式(小结)
2019/08/04 Javascript
原生JS与CSS实现软件卸载对话框功能
2019/12/05 Javascript
jQuery操作动画完整实例分析
2020/01/10 jQuery
公众号SVG动画交互实战代码
2020/05/31 Javascript
Vue 实现一个简单的鼠标拖拽滚动效果插件
2020/12/10 Vue.js
React中使用Vditor自定义图片详解
2020/12/25 Javascript
Python SQLite3数据库日期与时间常见函数用法分析
2017/08/14 Python
Python内置random模块生成随机数的方法
2019/05/31 Python
python 弹窗提示警告框MessageBox的实例
2019/06/18 Python
Python Django框架url反向解析实现动态生成对应的url链接示例
2019/10/18 Python
俄罗斯极限运动网上商店:Board Shop №1
2020/12/18 全球购物
酒店管理专业毕业生推荐信
2013/11/10 职场文书
执行力心得体会
2013/12/31 职场文书
公司授权委托书范文
2014/08/02 职场文书
工作失误检讨书范文
2015/01/26 职场文书
公务员廉洁从政心得体会
2016/01/19 职场文书
react 项目中引入图片的几种方式
2021/06/02 Javascript
win sever 2022如何占用操作主机角色
2022/06/25 Servers