From 14849f41d5b240a8f5d429d29af817bdf502af60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=96=AF=E7=8B=82=E7=9A=84=E7=8B=AE=E5=AD=90li?= <15040126243@163.com> Date: Mon, 14 Nov 2022 11:49:30 +0800 Subject: [PATCH] =?UTF-8?q?add=20=E6=96=B0=E5=A2=9E=20ruoyi-monitor=20?= =?UTF-8?q?=E7=9B=91=E6=8E=A7=E6=9C=8D=E5=8A=A1=20=E6=8F=90=E4=BE=9B=20pro?= =?UTF-8?q?metheus=20http=5Fsd=20=E6=9C=8D=E5=8A=A1=E5=8F=91=E7=8E=B0?= =?UTF-8?q?=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/PrometheusController.java | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 ruoyi-visual/ruoyi-monitor/src/main/java/com/ruoyi/modules/monitor/controller/PrometheusController.java diff --git a/ruoyi-visual/ruoyi-monitor/src/main/java/com/ruoyi/modules/monitor/controller/PrometheusController.java b/ruoyi-visual/ruoyi-monitor/src/main/java/com/ruoyi/modules/monitor/controller/PrometheusController.java new file mode 100644 index 00000000..3d438efc --- /dev/null +++ b/ruoyi-visual/ruoyi-monitor/src/main/java/com/ruoyi/modules/monitor/controller/PrometheusController.java @@ -0,0 +1,67 @@ +package com.ruoyi.modules.monitor.controller; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 对接 prometheus + * + * @author Lion Li + */ +@Slf4j +@RestController +@RequestMapping("/actuator/prometheus") +public class PrometheusController { + + @Autowired + private DiscoveryClient discoveryClient; + + /** + * 从注册中心获取所有服务组装成 prometheus 的数据结构 + */ + @GetMapping("/sd") + public List> sd() { + List services = discoveryClient.getServices(); + if (services == null || services.isEmpty()) { + return new ArrayList<>(0); + } + List> list = new ArrayList<>(); + for (String service : services) { + List instances = discoveryClient.getInstances(service); + List targets = instances.stream().map(i -> i.getHost() + ":" + i.getPort()).collect(Collectors.toList()); + + Map labels = new HashMap<>(2); + // 数据来源(区分异地使用) + // labels.put("__meta_datacenter", "beijing"); + // 服务名 + labels.put("__meta_prometheus_job", service); + Map group = new HashMap<>(2); + group.put("targets", targets); + group.put("labels", labels); + list.add(group); + } + return list; + } + + /** + * 接收 prometheus 报警消息 + * + * @param message 消息体 + */ + @PostMapping("/alerts") + public ResponseEntity alerts(@RequestBody String message) { + log.info("[prometheus] alert =>" + message); + return ResponseEntity.ok().build(); + } + +}