Spring Boot Admin 监控告警_springboot-admin自定义cpu告警-程序员宅基地

技术标签: JAVA  spring boot  SpringBoot  

Spring Boot Admin 监控告警

要进行监控,需要两个Project,一个是Admin Server端,负责监控Spring boot的项目,另一个是Admin Client端,是被监控的Spring boot服务。当然也可以一个项目同时做服务端和客户端,监控自己的本项目服务;

1.这里提供的是两个服务,首先新建一个server端的springboot项目

在这里插入图片描述

2.server端pom文件配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>spring-boot-admin-server</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-boot-admin-server</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>de.codecentric</groupId>
			<artifactId>spring-boot-admin-starter-server</artifactId>
			<version>2.2.2</version>
		</dependency>
		<!--监控-->
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-actuator</artifactId>
         </dependency>

         <dependency>
             <groupId>de.codecentric</groupId>
             <artifactId>spring-boot-admin-server-ui</artifactId>
             <version>2.2.2</version>
         </dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

3.server端application.yml文件配置

 spring:
   application:
     name: admin-server
 server:
   port: 9090

4.server端启动类添加注解 @EnableAdminServer

@EnableAdminServer

5.server端启动项目

在这里插入图片描述

6.新建client端,一个springboot项目即可

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>spring-boot-admin-server</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-boot-admin-server</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>de.codecentric</groupId>
			<artifactId>spring-boot-admin-starter-client</artifactId>
			<version>2.2.2</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

7.client端yml文件配置

server:
  port: 8800
spring:
  boot:
    admin:
      client:
        url: http://localhost:9090

8.client端然后启动,查看监听

在这里插入图片描述

配置调用admin的监控接口,实现判断

-达到百分之多少的时候会触发自定义报警消息提示,可配置到配置文件中

import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.face.ele.common.utils.IpInfoUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author weijianxing
 * @description: TODO
 * @date 2021/1/21 15:38
 */
@RestController
@RequestMapping("xboot/jvmMemory")
@Slf4j
public class JvmWarnMonitor {
    

	@Autowired
	private IpInfoUtil ipInfoUtil;

	@Value("${server.port}")
	private String WARN_PORT;
	@Value("${xboot.jvmMemoryLimit}")
	private double jvmMemoryLimit;

	@GetMapping("/getJvmMemory")
	@ApiOperation("获取jvm内存情况")
	public boolean getJvmMemory() throws IOException{
    
		InetAddress address=InetAddress.getLocalHost();
		//System.out.println(address.toString().split("/")[1]);
		String WARN_IP= address.toString().split("/")[1];//ipInfoUtil.getIpAddr(request);
		//JVM最大内存
		final String MAX_MEMORY = "/xboot/actuator/metrics/jvm.memory.max";
		//JVM已使用的内存
		final String USED_MEMORY = "/xboot/actuator/metrics/jvm.memory.used";
		//可供JVM用的内存
		final String FREE_MEMORY = "/xboot/actuator/metrics/jvm.memory.committed";

		//拼接接口路径地址
		String host1="http://"+WARN_IP+":"+WARN_PORT+"/"+MAX_MEMORY;
		String host2="http://"+WARN_IP+":"+WARN_PORT+"/"+USED_MEMORY;
		String host3="http://"+WARN_IP+":"+WARN_PORT+"/"+FREE_MEMORY;

		//拿到MAX_MEMORY
		Object model1=JvmWarnMonitor.jvmMsg(host1);
		Map<String,List<Map>> map=(Map)model1;
		String maxMemory=map.get("measurements").get(0).get("value").toString();

		//拿到USED_MEMORY
		Object model2=JvmWarnMonitor.jvmMsg(host2);
		Map<String,List<Map>> map2=(Map)model2;
		String usedMemory=map2.get("measurements").get(0).get("value").toString();

		//FREE_MEMORY
		Object model3=JvmWarnMonitor.jvmMsg(host3);
		Map<String,List<Map>> map3=(Map)model3;
		String freeMemory=map3.get("measurements").get(0).get("value").toString();

		//判断当jvm内存达到90% 进行报警
		double used= Double.parseDouble(usedMemory) ;
		double max= Double.parseDouble(maxMemory)*(jvmMemoryLimit/100) ;

		//然后开始判断,如果有超过的
		if(used>=max){
    
			log.info("内存超出"+jvmMemoryLimit+"%");
			log.info("maxMemory"+maxMemory);
			log.info("usedMemory"+usedMemory);
			log.info("freeMemory"+freeMemory);
			return true;
		}else{
    
			return false;
		}

	}

	/**
	 * 获得所有报警类别
	 * @return
	 * @throws IOException
	 */
	public static Object jvmMsg(String url) throws IOException{
    

		RequestBuilder builder = RequestBuilder.get().setUri(url);

		//HttpUriRequest httpRequest = builder.setEntity(new StringEntity(JSON.toJSONString(requestObject), "utf-8")).build();
		//请求设置
		HttpUriRequest httpRequest = builder.setEntity(new StringEntity("", "utf-8")).build();
		//建立请求连接
		CloseableHttpClient httpclient = HttpClients.custom().build();
		CloseableHttpResponse response = httpclient.execute(httpRequest);
		HttpEntity entity = response.getEntity();
		//返回结果信息
		byte[] data = EntityUtils.toByteArray(entity);
		//返回到页面结果
		Object obj=JSON.parse(new String(data));
		return obj;
	}



	@GetMapping("/testMemory")
	@ApiOperation("测试jvm_heap溢出")
	public String testMemory() throws IOException {
    
		int i=0;
		ArrayList<byte[]> a=new ArrayList<byte[]>();
		//调用是否超出规定范围,满足了就不要死循环了
		boolean flag=this.getJvmMemory();
		while (!flag) {
    
			try {
    
				boolean flag2=this.getJvmMemory();
				if(flag2){
    
					break;
				}
				Thread.sleep(500);
				a.add(new byte[1024*1024]);
				i++;
				System.out.println("添加"+i+"M");

			} catch (InterruptedException e) {
    
				e.printStackTrace();
			}
		}
		log.info("已经溢出,结束测试");
		return "已经溢出,结束测试;已添加"+i+"M";
	}


	public static void main(String[] args) throws IOException {
    
		/*String usedMemory="5.619843071E9";
		String maxMemory="10.123";
		double jvmMemoryLimit=50;
		double used= Double.parseDouble(usedMemory) ;
		double max= Double.parseDouble(maxMemory)* (jvmMemoryLimit/100);

		//然后开始判断,如果有超过的
		if(used>=max){
			System.out.println("超出");
		}*/
		/*InetAddress address=InetAddress.getLocalHost();
		System.out.println(address.toString().split("/")[1]);*/


		/*//JVM最大内存
		final String MAX_MEMORY = "/xboot/actuator/metrics/jvm.memory.max";
		//JVM已使用的内存
		final String USED_MEMORY = "/xboot/actuator/metrics/jvm.memory.used";
		//可供JVM用的内存
		final String FREE_MEMORY = "/xboot/actuator/metrics/jvm.memory.committed";

		//拼接接口路径地址
		String host1="http://127.0.0.1:8877/"+MAX_MEMORY;
		String host2="http://127.0.0.1:8877/"+USED_MEMORY;
		String host3="http://127.0.0.1:8877/"+FREE_MEMORY;
		//拿到MAX_MEMORY
		Object model1=JvmWarnMonitor.jvmMsg(host1);
		Map<String,List<Map>> map=(Map)model1;

		Object maxMemory=map.get("measurements").get(0).get("value");
		System.out.println("maxMemory"+maxMemory);
		//拿到USED_MEMORY
		Object model2=JvmWarnMonitor.jvmMsg(host2);
		Map<String,List<Map>> map2=(Map)model2;

		Object usedMemory=map2.get("measurements").get(0).get("value");
		System.out.println("usedMemory"+usedMemory);
		//FREE_MEMORY
		Object model3=JvmWarnMonitor.jvmMsg(host3);
		Map<String,List<Map>> map3=(Map)model3;

		Object freeMemory=map3.get("measurements").get(0).get("value");
		System.out.println("freeMemory"+freeMemory);*/
	}
}

配置的yml文件

jvmMemoryLimit: 50 #超出最大值的百分比

可以调用测试jvm内存溢出的接口(上面代码)
http://localhost:8877/xboot/jvmMemory/testMemory 即可
然后在页面不断刷新 http://localhost:8877/xboot/getJvmMemory 接口可查出是否报警

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weijx_/article/details/112858379

智能推荐

我的一个关于文件的程序 - [C语言]_fseek(fp,0l,2)-程序员宅基地

文章浏览阅读6.3k次。 2005-09-05我的一个关于文件的程序 - [C语言]#includevoid main(){char ch;FILE* fp;if((fp=fopen("test.txt","r"))==NULL){printf("error");exit(1);}fseek(fp,0L,2);while((fseek(fp,-1L,1))!=-1){ch=fgetc(fp);pu_fseek(fp,0l,2)

oracle 设置查询条数,SQL、MySQL、Oracle、 Sqlite、Informix数据库查询指定条数数据的方法...-程序员宅基地

文章浏览阅读674次。SQL查询前10条的方法为:select top X * from table_name--查询前X条记录,可以改成需要的数字,比如前10条。select top X * from table_name order by colum_name desc--按colum_name属性降序排序查询前X条记录,“order by” 后紧跟要排序的属性列名,其中desc表示降序,asc表示升序(默认也..._oracle怎么用语句设置查询结果数量

课程设计之第二次冲刺----第九天-程序员宅基地

文章浏览阅读58次。讨论成员:罗凯旋、罗林杰、吴伟锋、黎文衷讨论完善APP,调试功能。转载于:https://www.cnblogs.com/383237360q/p/5011594.html

favicon.ico 图标及时更新问题_win 软件开发 ico图标多久更新-程序员宅基地

文章浏览阅读5.4k次。首先看你 favicon.ico 图标文件引入路径是否正确然后 看ico文件能否正常打开,这两个没问题的话,在地址栏直接输入你的域名 http://xxx.com/favicon.ico 注意 此刻可能还是 之前的ico图标 不要着急 刷新一下 试试 完美解决 清除程序缓存_win 软件开发 ico图标多久更新

手工物理删除Oracle归档日志RMAN备份报错_rman 说明与资料档案库中在任何归档日志都不匹配-程序员宅基地

文章浏览阅读2.1k次。Oracle归档日志删除我们都都知道在controlfile中记录着每一个archivelog的相关信息,当然们在OS下把这些物理文件delete掉后,在我们的controlfile中仍然记录着这些archivelog的信息,在oracle的OEM管理器中有可视化的日志展现出,当我们手工清除 archive目录下的文件后,这些记录并没有被我们从controlfile中清除掉,也就是or_rman 说明与资料档案库中在任何归档日志都不匹配

命令提示符_命令提示符文件开头-程序员宅基地

文章浏览阅读706次。命令提示符:[ root@localhost桌面] #[用户名@主机名 当前所在位置] #(超级用户) KaTeX parse error: Expected 'EOF', got '#' at position 25: …用户: #̲ su 用户名 //切… su密码:[ root@cml桌面] #临时提升为root权限:# sudo 命令..._命令提示符文件开头

随便推点

android+打包+不同app,基于Gradle的Android应用打包实践-程序员宅基地

文章浏览阅读152次。0x01 基本项目结构使用Android Studio创建的Android项目会划分成三个层级:project : settings.gradle定义了构建应用时包含了哪些模块;build.gradle定义了适用于项目中所有模块的构建配置module : 可以是一个app类型的module,对应生成apk应用;也可以是一个lib类型的module,对应生成aar包. 每个module中包含的bui..._android多个应用 gradle 怎么打包指定的应用

qsort实现顺序与逆序/排整型,字符串数组,字符数组,结构体类型数组的名字排序,年龄排序等_qsort反向排序-程序员宅基地

文章浏览阅读599次,点赞12次,收藏11次。前言:通常我们排序都需要创建一个函数实现排序,但当我们排完整型数组时,想要排字符串呢?那需要重新创建一个函数,完善它的功能,进而实现排字符串,这样非常繁琐,但是有一个函数可以帮我们实现传什么,排什么;qsort的传参:(1️⃣,2️⃣,3️⃣,4️⃣) (首元素地址,排序的元素个数,每个元素的大小,指向比较两个元素的函数的指针)1️⃣2️⃣3️⃣4️⃣的传参方法,下面介绍:…整型数组:......_qsort反向排序

MVC绕过登陆界面验证时HttpContext.Current.User.Identity.Name取值为空问题解决方法_mvc 不验证登陆-程序员宅基地

文章浏览阅读355次。MVC绕过登陆界面验证时HttpContext.Current.User.Identity.Name取值为空问题解决方法_mvc 不验证登陆

Java中DO、DTO、BO、AO、VO、POJO、Query 命名规范_dto命名规范-程序员宅基地

文章浏览阅读7.6k次,点赞2次,收藏8次。1.分层领域模型规约: • DO( Data Object):与数据库表结构一一对应,通过DAO层向上传输数据源对象。 • DTO( Data Transfer Object):数据传输对象,Service或Manager向外传输的对象。 • BO( Business Object):业务对象。 由Service层输出的封装业务逻辑的对象。 • AO( Ap..._dto命名规范

1015. Reversible Primes (20) PAT甲级刷题_pat甲级1015-程序员宅基地

文章浏览阅读91次。A reversible prime in any number system is a prime whose "reverse" in that number system is also a prime. For example in the decimal system 73 is a reversible prime because its reverse 37 is also a pr..._pat甲级1015

ABAP接口之Http发送json报文_abap http 转换为json输出-程序员宅基地

文章浏览阅读1.5k次。ABAP接口之Http发送json报文abap 调用http 发送 json 测试函数SE11创建结构:zsmlscpnoticeSE37创建函数:zqb_test_http_fuc1FUNCTIONzqb_test_http_fuc1.*"----------------------------------------------------------------..._abap http 转换为json输出