searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

VictoriaMetrics vmagent接入指南

2023-05-26 11:33:27
153
0
@RestController
public class CpuAndMemoryDemo {
  final long GB = 1024 * 1024 * 1024;
  String hostAd = InetAddress.getLocalHost().getHostAddress();
​
  private VmAgentPushWay vmwy;
​
  public CpuAndMemoryDemo(VmAgentPushWay vmwy) throws UnknownHostException {
      this.vmwy = vmwy;
   }
​
  //指标埋点
  @Scheduled(cron="0/5 * * * * ?")
  public void pushData() throws IOException {
      System.out.println("开始写入");
      //--开始获取业务指标信息。
      OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
      String osJson = JSON.toJSONString(operatingSystemMXBean);
      JSONObject jsonObject = JSON.parseObject(osJson);
      double processCpuLoad = jsonObject.getDouble("processCpuLoad") * 100;
      double systemCpuLoad = jsonObject.getDouble("systemCpuLoad") * 100;
      Long totalPhysicalMemorySize = jsonObject.getLong("totalPhysicalMemorySize");
      Long freePhysicalMemorySize = jsonObject.getLong("freePhysicalMemorySize");
      double totalMemory = 1.0 * totalPhysicalMemorySize / GB;
      double freeMemory = 1.0 * freePhysicalMemorySize / GB;
      double memoryUseRatio = 1.0 * (totalPhysicalMemorySize - freePhysicalMemorySize) / totalPhysicalMemorySize * 100;
      ////--获取业务指标信息结束。
      //自定义labs标签信息,如业务入参,uuid等都可以放入labs中。
      Map labs = new HashMap();
      labs.put("host_address",hostAd);
      labs.put("resources_unit","cpu_unit");
      labs.put("job","localhost_resources_demo");
      //调用接口。
      String result = vmwy.vmAgentCommonPost("localhost_resources_info", labs,systemCpuLoad);
      System.out.println("结果:"+result);
      System.out.println("写入结束"+systemCpuLoad+";");
   }
​
}

Pull模式

Java SpringBoot 2.x

基于micrometer库实现,提供极简化exporter实现。不支持动态Label,因此仅适用于自监控,不适用于业务监控。

1、引入如下pom依赖。

<!-- Spring boot actuator to expose metrics endpoint -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Micormeter core dependecy -->
<dependency>
   <groupId>io.micrometer</groupId>
   <artifactId>micrometer-core</artifactId>
</dependency>

2、增加如下配置。

management:
endpoints:
  prometheus:
    id: springmetrics   #此处对应Prometheus的job名
  web:
     # base-path: /xueqiu # 修改actuator的路径名,建议根目录
    exposure:
      include: health,prometheus
      exclude: info,env,metrics,httptrace,threaddump,heapdump
    base-path: /
    path-mapping:
      prometheus: metrics
 ## 内置的检查项配置
metrics:
  enable:
    jvm: true
    logback: false
    files: false
    tomcat: true
    executor: true
    disk: true
    uptime: false
    integration: true

3、编写自定义监控指标:

@Component
@NonNullApi
@NonNullFields
public class HostMonitorMetircs implements MeterBinder {
   private HostQueryService hostQueryService;
   private final Iterable<Tag> tags = null;
 
   @Autowired
   public HostMonitorMetircs(HostQueryService hostQueryService) {
       this.hostQueryService = hostQueryService;
  }
/**
* 此方法仅在初始化时执行一次,因此不支持动态新增指标,请注意!
**/
   @Override
   public void bindTo(MeterRegistry meterRegistry) {
       for (String s: hostQueryService.getHostUuids()) {
           Iterable<Tag> tagsWithPath = Tags.concat(null, new String[]{"HostUuid", s});
           Gauge.builder("host.disk.free", hostQueryService, HostQueryService::getHostCpuUtil).tags(tagsWithPath).description("Usable space for path").baseUnit("bytes").strongReference(true).register(meterRegistry);
      }        
  }
}

监控指标获取实现类:

@Service
public class HostQueryService {
   public Double getHostCpuUtil() {
       //此处写具体实现
       return new Random().nextDouble();
  }
   
   public List<String> getHostUuids(){
       list = new ArrayList<>();
       list.add(UUID.randomUUID().toString());
       list.add(UUID.randomUUID().toString());
       return  list;
  }
}

全局自定义新增label(可选):

@Configuration
public class CustomMeterRegistryCustomizer implements MeterRegistryCustomizer<MeterRegistry> {
   @Value("${spring.application.name}")
   private String applicationName;
​
   @Override
   public void customize(MeterRegistry registry) {
       //默认加label
       registry.config()
              .commonTags("host_name", "localhost")
              .commonTags("application", applicationName);;
  }
}

过滤器(可选):

@Configuration
public class CustomMeterFilter implements MeterFilter {
​
   @Override
   public MeterFilterReply accept(Meter.Id id) {
       return MeterFilterReply.ACCEPT;
       /*if (id.getName().startsWith("host")) {
           return MeterFilterReply.ACCEPT;
       }
       return MeterFilterReply.DENY;*/
  }
}

4、启动工程,访问http://localhost:xxxx/metrics,即可查看输出的指标。

 

Python

GitHub - prometheus/client_python: Prometheus instrumentation library for Python applications

 

GO

GitHub - prometheus/client_golang: Prometheus instrumentation library for Go applications

官方demo:

package main

import (
	"log"
	"net/http"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
	cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "cpu_temperature_celsius",
		Help: "Current temperature of the CPU.",
	})
	hdFailures = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "hd_errors_total",
			Help: "Number of hard-disk errors.",
		},
		[]string{"device"},
	)
)

func main() {
	reg := prometheus.NewRegistry()
	reg.MustRegister(cpuTemp)
	reg.MustRegister(hdFailures)

	cpuTemp.Set(65.3)
	cpuTemp.Set(65.8)

	go func() {
		for {
			hdFailures.With(prometheus.Labels{"device": "/dev/sda"}).Inc()
			hdFailures.With(prometheus.Labels{"device": "/dev/sdb"}).Inc()
			time.Sleep(time.Second * 5)
		}
	}()

	http.Handle("/metrics", promhttp.InstrumentMetricHandler(
		reg, promhttp.HandlerFor(reg, promhttp.HandlerOpts{}),
	))
	log.Fatal(http.ListenAndServe(":8018", nil))
}

 

Push模式

vmagent只能接受以/api/v1/import/prometheus作为接受推送的路径,不支持pushgateway格式。例如:

curl -d 'foo{bar="baz"} 123' -X POST 'http://localhost:8428/api/v1/import/prometheus'

注意:VictoriaMetrics并未将Prometheus的四种指标类型进行单独处理,而是将这四种指标类型按统一的单行文本模型处理,模型如下:

metric_name [
"{" label_name "=" `"` label_value `"` { "," label_name "=" `"` label_value `"` } [ "," ] "}"
] value [ timestamp ]

形如:

{"metric":{"__name__":"bid","market":"NASDAQ","ticker":"MSFT"},"values":[1.67],"timestamps":[1583865146520]}
{"metric":{"__name__":"bid","market":"NYSE","ticker":"GOOG"},"values":[4.56],"timestamps":[1583865146495]}
{"metric":{"__name__":"ask","market":"NASDAQ","ticker":"MSFT"},"values":[3.21],"timestamps":[1583865146520]}
{"metric":{"__name__":"ask","market":"NYSE","ticker":"GOOG"},"values":[1.23],"timestamps":[1583865146495]}
  1. metric_name 和 label_name 带有通常的 Prometheus 表达式语言限制。

  2. label_value 可以是任何 UTF-8 字符序列,但反斜杠 ()、双引号 (") 和换行 (\n) 字符必须分别转义为 \\、\" 和 \n。

  3. value 是一个浮点数,由 Go 的 ParseFloat() 函数表示。除了标准数值之外,NaN、+Inf 和 -Inf 是分别表示非数字、正无穷大和负无穷大的有效值。

  4. 时间戳是一个 int64(自纪元以来的毫秒数,即 1970-01-01 00:00:00 UTC,不包括闰秒),由 Go 的 ParseInt() 函数表示。

Java SpringBoot 2.x

已简单封装了一个VmAgentPushWay的对象类,大家在通过java推送数据时无需关注格式。 只需要调用VmAgentPushWay类的vmAgentCommonPost方法,方法注意3个入参,最终对象类自动组装好push模式的数据样式,并推送的接口地址。 入参: String jobName:您的metric_name Map labs:您的标签信息,支持同时放入多个标签。 double value:监控指标值。 按以上格式封装参数调用方法即可(详细可参考java push demo示例CpuAndMemoryDemo)。

push调用示例方法:

@RestController
public class CpuAndMemoryDemo {
  final long GB = 1024 * 1024 * 1024;
  String hostAd = InetAddress.getLocalHost().getHostAddress();
​
  private VmAgentPushWay vmwy;
​
  public CpuAndMemoryDemo(VmAgentPushWay vmwy) throws UnknownHostException {
      this.vmwy = vmwy;
   }
​
  //指标埋点
  @Scheduled(cron="0/5 * * * * ?")
  public void pushData() throws IOException {
      System.out.println("开始写入");
      //--开始获取业务指标信息。
      OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
      String osJson = JSON.toJSONString(operatingSystemMXBean);
      JSONObject jsonObject = JSON.parseObject(osJson);
      double processCpuLoad = jsonObject.getDouble("processCpuLoad") * 100;
      double systemCpuLoad = jsonObject.getDouble("systemCpuLoad") * 100;
      Long totalPhysicalMemorySize = jsonObject.getLong("totalPhysicalMemorySize");
      Long freePhysicalMemorySize = jsonObject.getLong("freePhysicalMemorySize");
      double totalMemory = 1.0 * totalPhysicalMemorySize / GB;
      double freeMemory = 1.0 * freePhysicalMemorySize / GB;
      double memoryUseRatio = 1.0 * (totalPhysicalMemorySize - freePhysicalMemorySize) / totalPhysicalMemorySize * 100;
      ////--获取业务指标信息结束。
      //自定义labs标签信息,如业务入参,uuid等都可以放入labs中。
      Map labs = new HashMap();
      labs.put("host_address",hostAd);
      labs.put("resources_unit","cpu_unit");
      labs.put("job","localhost_resources_demo");
      //调用接口。
      String result = vmwy.vmAgentCommonPost("localhost_resources_info", labs,systemCpuLoad);
      System.out.println("结果:"+result);
      System.out.println("写入结束"+systemCpuLoad+";");
   }
​
}

封装类VmAgentPushWay:

@Component
public class VmAgentPushWay {
​
  @Value("${common.vmagent.hostUrl}")
   String url;
​
  public String vmAgentCommonPost(String jobName, Map<String,String> labs, double value) {
      if(jobName==null||"".equals(jobName)||labs==null||labs.size()==0){
          return "jobName或者labs不能为空";
       }
      String info = jobName+"{";
      Set<String> set = labs.keySet();
      for (String key : set) {
          info = info + key + "=" + "\"" + labs.get(key) + "\",";
       }
      info = info.substring(0,info.length()-1) + "} " + value;
​
      System.out.println(info);
      HttpClient httpClient= HttpClients.createDefault();
      HttpPost httpPost=new HttpPost(this.url);
      httpPost.setEntity(new StringEntity(info, "UTF-8"));
      httpPost.addHeader(HTTP.CONTENT_TYPE,"application/json");
      HttpResponse httpResponse= null;
      try {
          httpResponse = httpClient.execute(httpPost);
          int code = httpResponse.getStatusLine().getStatusCode();
          if(code/100==2){
              return "成功!";
           }else{
              return EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
           }
       } catch (Exception e) {
          return(e.getMessage());
       }
​
   }
}

Python

需自行封装

Go

VmAgentCommonPost:

import (
	"bytes"
	"errors"
	"fmt"
	"net/http"
	"strings"
)

var (
	url = "http://localhost:8428/api/v1/import/prometheus"
)

func VmAgentCommonPost(jobName string, labs map[string]string, value float64) (string, error) {
	if jobName == "" || labs == nil || len(labs) == 0 {
		return "", errors.New("jobName或者labs不能为空")
	}
	var builder strings.Builder
	builder.WriteString(jobName + "{")
	for key, value := range labs {
		builder.WriteString(key + "=" + "\"" + value + "\",")
	}
	info := builder.String()
	info = info[:len(info)-1] + fmt.Sprintf("} %.2f", value)
	fmt.Println(info)
	requestBuf := bytes.NewBuffer([]byte(info))

	fmt.Printf("requestBuf: %v\n", requestBuf)

	resp, err := http.Post(url, "application/json", requestBuf)
	if err != nil {
		fmt.Println(err)
		return "", err
	}
	if resp.StatusCode/100 != 2 {
		return fmt.Sprintf("%v", resp.Body), err
	} else {
		return "Success!", nil
	}
}

 

应用自监控

可使用Pull模式,三种语言接入均可完美支持。

业务监控

Pull模式下,Java SpringBoot 2.x不支持!Python、Go均支持。

Push模式下,不限制语言,需按照规定格式进行http推送。

0条评论
0 / 1000
y****n
1文章数
0粉丝数
y****n
1 文章 | 0 粉丝
y****n
1文章数
0粉丝数
y****n
1 文章 | 0 粉丝
原创

VictoriaMetrics vmagent接入指南

2023-05-26 11:33:27
153
0
@RestController
public class CpuAndMemoryDemo {
  final long GB = 1024 * 1024 * 1024;
  String hostAd = InetAddress.getLocalHost().getHostAddress();
​
  private VmAgentPushWay vmwy;
​
  public CpuAndMemoryDemo(VmAgentPushWay vmwy) throws UnknownHostException {
      this.vmwy = vmwy;
   }
​
  //指标埋点
  @Scheduled(cron="0/5 * * * * ?")
  public void pushData() throws IOException {
      System.out.println("开始写入");
      //--开始获取业务指标信息。
      OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
      String osJson = JSON.toJSONString(operatingSystemMXBean);
      JSONObject jsonObject = JSON.parseObject(osJson);
      double processCpuLoad = jsonObject.getDouble("processCpuLoad") * 100;
      double systemCpuLoad = jsonObject.getDouble("systemCpuLoad") * 100;
      Long totalPhysicalMemorySize = jsonObject.getLong("totalPhysicalMemorySize");
      Long freePhysicalMemorySize = jsonObject.getLong("freePhysicalMemorySize");
      double totalMemory = 1.0 * totalPhysicalMemorySize / GB;
      double freeMemory = 1.0 * freePhysicalMemorySize / GB;
      double memoryUseRatio = 1.0 * (totalPhysicalMemorySize - freePhysicalMemorySize) / totalPhysicalMemorySize * 100;
      ////--获取业务指标信息结束。
      //自定义labs标签信息,如业务入参,uuid等都可以放入labs中。
      Map labs = new HashMap();
      labs.put("host_address",hostAd);
      labs.put("resources_unit","cpu_unit");
      labs.put("job","localhost_resources_demo");
      //调用接口。
      String result = vmwy.vmAgentCommonPost("localhost_resources_info", labs,systemCpuLoad);
      System.out.println("结果:"+result);
      System.out.println("写入结束"+systemCpuLoad+";");
   }
​
}

Pull模式

Java SpringBoot 2.x

基于micrometer库实现,提供极简化exporter实现。不支持动态Label,因此仅适用于自监控,不适用于业务监控。

1、引入如下pom依赖。

<!-- Spring boot actuator to expose metrics endpoint -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Micormeter core dependecy -->
<dependency>
   <groupId>io.micrometer</groupId>
   <artifactId>micrometer-core</artifactId>
</dependency>

2、增加如下配置。

management:
endpoints:
  prometheus:
    id: springmetrics   #此处对应Prometheus的job名
  web:
     # base-path: /xueqiu # 修改actuator的路径名,建议根目录
    exposure:
      include: health,prometheus
      exclude: info,env,metrics,httptrace,threaddump,heapdump
    base-path: /
    path-mapping:
      prometheus: metrics
 ## 内置的检查项配置
metrics:
  enable:
    jvm: true
    logback: false
    files: false
    tomcat: true
    executor: true
    disk: true
    uptime: false
    integration: true

3、编写自定义监控指标:

@Component
@NonNullApi
@NonNullFields
public class HostMonitorMetircs implements MeterBinder {
   private HostQueryService hostQueryService;
   private final Iterable<Tag> tags = null;
 
   @Autowired
   public HostMonitorMetircs(HostQueryService hostQueryService) {
       this.hostQueryService = hostQueryService;
  }
/**
* 此方法仅在初始化时执行一次,因此不支持动态新增指标,请注意!
**/
   @Override
   public void bindTo(MeterRegistry meterRegistry) {
       for (String s: hostQueryService.getHostUuids()) {
           Iterable<Tag> tagsWithPath = Tags.concat(null, new String[]{"HostUuid", s});
           Gauge.builder("host.disk.free", hostQueryService, HostQueryService::getHostCpuUtil).tags(tagsWithPath).description("Usable space for path").baseUnit("bytes").strongReference(true).register(meterRegistry);
      }        
  }
}

监控指标获取实现类:

@Service
public class HostQueryService {
   public Double getHostCpuUtil() {
       //此处写具体实现
       return new Random().nextDouble();
  }
   
   public List<String> getHostUuids(){
       list = new ArrayList<>();
       list.add(UUID.randomUUID().toString());
       list.add(UUID.randomUUID().toString());
       return  list;
  }
}

全局自定义新增label(可选):

@Configuration
public class CustomMeterRegistryCustomizer implements MeterRegistryCustomizer<MeterRegistry> {
   @Value("${spring.application.name}")
   private String applicationName;
​
   @Override
   public void customize(MeterRegistry registry) {
       //默认加label
       registry.config()
              .commonTags("host_name", "localhost")
              .commonTags("application", applicationName);;
  }
}

过滤器(可选):

@Configuration
public class CustomMeterFilter implements MeterFilter {
​
   @Override
   public MeterFilterReply accept(Meter.Id id) {
       return MeterFilterReply.ACCEPT;
       /*if (id.getName().startsWith("host")) {
           return MeterFilterReply.ACCEPT;
       }
       return MeterFilterReply.DENY;*/
  }
}

4、启动工程,访问http://localhost:xxxx/metrics,即可查看输出的指标。

 

Python

GitHub - prometheus/client_python: Prometheus instrumentation library for Python applications

 

GO

GitHub - prometheus/client_golang: Prometheus instrumentation library for Go applications

官方demo:

package main

import (
	"log"
	"net/http"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
	cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "cpu_temperature_celsius",
		Help: "Current temperature of the CPU.",
	})
	hdFailures = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "hd_errors_total",
			Help: "Number of hard-disk errors.",
		},
		[]string{"device"},
	)
)

func main() {
	reg := prometheus.NewRegistry()
	reg.MustRegister(cpuTemp)
	reg.MustRegister(hdFailures)

	cpuTemp.Set(65.3)
	cpuTemp.Set(65.8)

	go func() {
		for {
			hdFailures.With(prometheus.Labels{"device": "/dev/sda"}).Inc()
			hdFailures.With(prometheus.Labels{"device": "/dev/sdb"}).Inc()
			time.Sleep(time.Second * 5)
		}
	}()

	http.Handle("/metrics", promhttp.InstrumentMetricHandler(
		reg, promhttp.HandlerFor(reg, promhttp.HandlerOpts{}),
	))
	log.Fatal(http.ListenAndServe(":8018", nil))
}

 

Push模式

vmagent只能接受以/api/v1/import/prometheus作为接受推送的路径,不支持pushgateway格式。例如:

curl -d 'foo{bar="baz"} 123' -X POST 'http://localhost:8428/api/v1/import/prometheus'

注意:VictoriaMetrics并未将Prometheus的四种指标类型进行单独处理,而是将这四种指标类型按统一的单行文本模型处理,模型如下:

metric_name [
"{" label_name "=" `"` label_value `"` { "," label_name "=" `"` label_value `"` } [ "," ] "}"
] value [ timestamp ]

形如:

{"metric":{"__name__":"bid","market":"NASDAQ","ticker":"MSFT"},"values":[1.67],"timestamps":[1583865146520]}
{"metric":{"__name__":"bid","market":"NYSE","ticker":"GOOG"},"values":[4.56],"timestamps":[1583865146495]}
{"metric":{"__name__":"ask","market":"NASDAQ","ticker":"MSFT"},"values":[3.21],"timestamps":[1583865146520]}
{"metric":{"__name__":"ask","market":"NYSE","ticker":"GOOG"},"values":[1.23],"timestamps":[1583865146495]}
  1. metric_name 和 label_name 带有通常的 Prometheus 表达式语言限制。

  2. label_value 可以是任何 UTF-8 字符序列,但反斜杠 ()、双引号 (") 和换行 (\n) 字符必须分别转义为 \\、\" 和 \n。

  3. value 是一个浮点数,由 Go 的 ParseFloat() 函数表示。除了标准数值之外,NaN、+Inf 和 -Inf 是分别表示非数字、正无穷大和负无穷大的有效值。

  4. 时间戳是一个 int64(自纪元以来的毫秒数,即 1970-01-01 00:00:00 UTC,不包括闰秒),由 Go 的 ParseInt() 函数表示。

Java SpringBoot 2.x

已简单封装了一个VmAgentPushWay的对象类,大家在通过java推送数据时无需关注格式。 只需要调用VmAgentPushWay类的vmAgentCommonPost方法,方法注意3个入参,最终对象类自动组装好push模式的数据样式,并推送的接口地址。 入参: String jobName:您的metric_name Map labs:您的标签信息,支持同时放入多个标签。 double value:监控指标值。 按以上格式封装参数调用方法即可(详细可参考java push demo示例CpuAndMemoryDemo)。

push调用示例方法:

@RestController
public class CpuAndMemoryDemo {
  final long GB = 1024 * 1024 * 1024;
  String hostAd = InetAddress.getLocalHost().getHostAddress();
​
  private VmAgentPushWay vmwy;
​
  public CpuAndMemoryDemo(VmAgentPushWay vmwy) throws UnknownHostException {
      this.vmwy = vmwy;
   }
​
  //指标埋点
  @Scheduled(cron="0/5 * * * * ?")
  public void pushData() throws IOException {
      System.out.println("开始写入");
      //--开始获取业务指标信息。
      OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
      String osJson = JSON.toJSONString(operatingSystemMXBean);
      JSONObject jsonObject = JSON.parseObject(osJson);
      double processCpuLoad = jsonObject.getDouble("processCpuLoad") * 100;
      double systemCpuLoad = jsonObject.getDouble("systemCpuLoad") * 100;
      Long totalPhysicalMemorySize = jsonObject.getLong("totalPhysicalMemorySize");
      Long freePhysicalMemorySize = jsonObject.getLong("freePhysicalMemorySize");
      double totalMemory = 1.0 * totalPhysicalMemorySize / GB;
      double freeMemory = 1.0 * freePhysicalMemorySize / GB;
      double memoryUseRatio = 1.0 * (totalPhysicalMemorySize - freePhysicalMemorySize) / totalPhysicalMemorySize * 100;
      ////--获取业务指标信息结束。
      //自定义labs标签信息,如业务入参,uuid等都可以放入labs中。
      Map labs = new HashMap();
      labs.put("host_address",hostAd);
      labs.put("resources_unit","cpu_unit");
      labs.put("job","localhost_resources_demo");
      //调用接口。
      String result = vmwy.vmAgentCommonPost("localhost_resources_info", labs,systemCpuLoad);
      System.out.println("结果:"+result);
      System.out.println("写入结束"+systemCpuLoad+";");
   }
​
}

封装类VmAgentPushWay:

@Component
public class VmAgentPushWay {
​
  @Value("${common.vmagent.hostUrl}")
   String url;
​
  public String vmAgentCommonPost(String jobName, Map<String,String> labs, double value) {
      if(jobName==null||"".equals(jobName)||labs==null||labs.size()==0){
          return "jobName或者labs不能为空";
       }
      String info = jobName+"{";
      Set<String> set = labs.keySet();
      for (String key : set) {
          info = info + key + "=" + "\"" + labs.get(key) + "\",";
       }
      info = info.substring(0,info.length()-1) + "} " + value;
​
      System.out.println(info);
      HttpClient httpClient= HttpClients.createDefault();
      HttpPost httpPost=new HttpPost(this.url);
      httpPost.setEntity(new StringEntity(info, "UTF-8"));
      httpPost.addHeader(HTTP.CONTENT_TYPE,"application/json");
      HttpResponse httpResponse= null;
      try {
          httpResponse = httpClient.execute(httpPost);
          int code = httpResponse.getStatusLine().getStatusCode();
          if(code/100==2){
              return "成功!";
           }else{
              return EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
           }
       } catch (Exception e) {
          return(e.getMessage());
       }
​
   }
}

Python

需自行封装

Go

VmAgentCommonPost:

import (
	"bytes"
	"errors"
	"fmt"
	"net/http"
	"strings"
)

var (
	url = "http://localhost:8428/api/v1/import/prometheus"
)

func VmAgentCommonPost(jobName string, labs map[string]string, value float64) (string, error) {
	if jobName == "" || labs == nil || len(labs) == 0 {
		return "", errors.New("jobName或者labs不能为空")
	}
	var builder strings.Builder
	builder.WriteString(jobName + "{")
	for key, value := range labs {
		builder.WriteString(key + "=" + "\"" + value + "\",")
	}
	info := builder.String()
	info = info[:len(info)-1] + fmt.Sprintf("} %.2f", value)
	fmt.Println(info)
	requestBuf := bytes.NewBuffer([]byte(info))

	fmt.Printf("requestBuf: %v\n", requestBuf)

	resp, err := http.Post(url, "application/json", requestBuf)
	if err != nil {
		fmt.Println(err)
		return "", err
	}
	if resp.StatusCode/100 != 2 {
		return fmt.Sprintf("%v", resp.Body), err
	} else {
		return "Success!", nil
	}
}

 

应用自监控

可使用Pull模式,三种语言接入均可完美支持。

业务监控

Pull模式下,Java SpringBoot 2.x不支持!Python、Go均支持。

Push模式下,不限制语言,需按照规定格式进行http推送。

文章来自个人专栏
文章 | 订阅
0条评论
0 / 1000
请输入你的评论
0
0