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中Collection的一些常用方法总结
Jun 13 Java/Android
springboot拦截器无法注入redisTemplate的解决方法
Jun 27 Java/Android
Spring Boot 实现敏感词及特殊字符过滤处理
Jun 29 Java/Android
jackson json序列化实现首字母大写,第二个字母需小写
Jun 29 Java/Android
Springboot使用Spring Data JPA实现数据库操作
Jun 30 Java/Android
使用@Value值注入及配置文件组件扫描
Jul 09 Java/Android
Lombok的详细使用及优缺点总结
Jul 15 Java/Android
idea 在springboot中使用lombok插件的方法
Aug 02 Java/Android
使用logback实现按自己的需求打印日志到自定义的文件里
Aug 30 Java/Android
SpringBoot+Redis实现布隆过滤器的示例代码
Mar 17 Java/Android
Java Spring Boot 正确读取配置文件中的属性的值
Apr 20 Java/Android
Mybatis-Plus 使用 @TableField 自动填充日期
Apr 26 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
php实现多维数组排序的方法示例
2017/03/23 PHP
PHP安装BCMath扩展的方法
2019/02/13 PHP
DWR Ext 加载数据
2009/03/22 Javascript
window.event.keyCode兼容IE和Firefox实现js代码
2013/05/30 Javascript
js读取被点击次数的简单实例(从数据库中读取)
2014/03/07 Javascript
jQuery过滤选择器详解
2015/01/13 Javascript
JQuery插件Quicksand实现超炫的动画洗牌效果
2015/05/03 Javascript
package.json文件配置详解
2017/06/15 Javascript
JS数组交集、并集、差集的示例代码
2017/08/23 Javascript
深入理解React高阶组件
2017/09/28 Javascript
原生javascript实现连连看游戏
2019/01/03 Javascript
js中let能否完全替代IIFE
2019/06/15 Javascript
jquery弹窗时禁止body滚动条滚动的例子
2019/09/21 jQuery
JS实现旋转木马轮播图
2020/01/01 Javascript
js实现点赞按钮功能的实例代码
2020/03/06 Javascript
vue 里面的 $forceUpdate() 强制实例重新渲染操作
2020/09/21 Javascript
python实现文件名批量替换和内容替换
2014/03/20 Python
Windows下用py2exe将Python程序打包成exe程序的教程
2015/04/08 Python
Python reduce()函数的用法小结
2017/11/15 Python
python使用pil进行图像处理(等比例压缩、裁剪)实例代码
2017/12/11 Python
讲解Python3中NumPy数组寻找特定元素下标的两种方法
2019/08/04 Python
python生成特定分布数的实例
2019/12/05 Python
tensorflow获取预训练模型某层参数并赋值到当前网络指定层方式
2020/01/24 Python
Python多线程Threading、子线程与守护线程实例详解
2020/03/24 Python
python与idea的集成的实现
2020/11/20 Python
Python json解析库jsonpath原理及使用示例
2020/11/25 Python
Python+Opencv实现把图片、视频互转的示例
2020/12/17 Python
英国在线药房和在线药剂师:Chemist 4 U
2020/01/05 全球购物
就业导师推荐信范文
2015/03/27 职场文书
投资公司董事长岗位职责
2015/04/16 职场文书
暑期社会实践新闻稿
2015/07/17 职场文书
联村联户简报
2015/07/21 职场文书
学校教学管理制度
2015/08/06 职场文书
python中requests库+xpath+lxml简单使用
2021/04/29 Python
深入解读Java三大集合之map list set的用法
2021/11/11 Java/Android
解决Redis启动警告问题
2022/02/24 Redis