浏览代码

移除core-metrics模块,starter-api增加actuator依赖,Aac注解移除metrics参数

Signed-off-by: luoshi <luoshi@qmth.com.cn>
luoshi 2 年之前
父节点
当前提交
1f46d360c3

+ 0 - 38
core-metrics/pom.xml

@@ -1,38 +0,0 @@
-<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-    <modelVersion>4.0.0</modelVersion>
-    <parent>
-        <groupId>com.qmth.boot</groupId>
-        <artifactId>qmth-boot</artifactId>
-        <version>1.0.4</version>
-    </parent>
-    <artifactId>core-metrics</artifactId>
-    <name>core-metrics</name>
-
-    <dependencies>
-        <dependency>
-            <groupId>com.qmth.boot</groupId>
-            <artifactId>core-models</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-autoconfigure</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-validation</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>junit</groupId>
-            <artifactId>junit</artifactId>
-            <scope>test</scope>
-        </dependency>
-    </dependencies>
-
-</project>

+ 0 - 19
core-metrics/src/main/java/com/qmth/boot/core/metrics/config/MetricsAutoConfiguration.java

@@ -1,19 +0,0 @@
-package com.qmth.boot.core.metrics.config;
-
-import com.qmth.boot.core.metrics.service.MetricsService;
-import com.qmth.boot.core.metrics.service.impl.MemoryMetricsService;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-
-@Configuration
-@ComponentScan("com.qmth.boot.core.metrics.*")
-public class MetricsAutoConfiguration {
-
-    @Bean
-    @ConditionalOnMissingBean(MetricsService.class)
-    public MetricsService metricsService(MetricsProperties metricsProperties) {
-        return new MemoryMetricsService(metricsProperties);
-    }
-}

+ 0 - 38
core-metrics/src/main/java/com/qmth/boot/core/metrics/config/MetricsProperties.java

@@ -1,38 +0,0 @@
-package com.qmth.boot.core.metrics.config;
-
-import com.qmth.boot.core.constant.CoreConstant;
-import org.springframework.boot.context.properties.ConfigurationProperties;
-import org.springframework.stereotype.Component;
-import org.springframework.validation.annotation.Validated;
-
-import javax.validation.constraints.NotEmpty;
-import java.time.Duration;
-
-/**
- * 统计工具参数设置
- */
-@Component
-@ConfigurationProperties(prefix = CoreConstant.CONFIG_PREFIX + ".metrics")
-@Validated
-public class MetricsProperties {
-
-    /**
-     * 默认时间分组,按0~10ms,10ms~100ms,100ms~500ms,500ms~1s,1s~10s,>10s分为6个档次
-     */
-    @NotEmpty
-    private Duration[] timeGroup = new Duration[] { Duration.ofMillis(10), Duration.ofMillis(100),
-            Duration.ofMillis(500), Duration.ofSeconds(1), Duration.ofSeconds(10) };
-
-    /**
-     * 获取响应时间分组间隔
-     *
-     * @return
-     */
-    public Duration[] getTimeGroup() {
-        return timeGroup;
-    }
-
-    public void setTimeGroup(Duration[] timeGroup) {
-        this.timeGroup = timeGroup;
-    }
-}

+ 0 - 39
core-metrics/src/main/java/com/qmth/boot/core/metrics/model/MetricsResult.java

@@ -1,39 +0,0 @@
-package com.qmth.boot.core.metrics.model;
-
-import java.util.Map;
-
-/**
- * 单个统计点的统计结果
- */
-public class MetricsResult {
-
-    private String endpoint;
-
-    private Map<Integer, Long> status;
-
-    private Map<TimeRange, Long> time;
-
-    public String getEndpoint() {
-        return endpoint;
-    }
-
-    public void setEndpoint(String endpoint) {
-        this.endpoint = endpoint;
-    }
-
-    public Map<Integer, Long> getStatus() {
-        return status;
-    }
-
-    public void setStatus(Map<Integer, Long> status) {
-        this.status = status;
-    }
-
-    public Map<TimeRange, Long> getTime() {
-        return time;
-    }
-
-    public void setTime(Map<TimeRange, Long> time) {
-        this.time = time;
-    }
-}

+ 0 - 54
core-metrics/src/main/java/com/qmth/boot/core/metrics/model/TimeRange.java

@@ -1,54 +0,0 @@
-package com.qmth.boot.core.metrics.model;
-
-/**
- * 以毫秒为单位的统计时间范围
- */
-public class TimeRange {
-
-    private long ge;
-
-    private long lt;
-
-    public TimeRange(long ge, long lt) {
-        this.ge = ge;
-        this.lt = lt;
-    }
-
-    public long getGe() {
-        return ge;
-    }
-
-    public long getLt() {
-        return lt;
-    }
-
-    @Override
-    public String toString() {
-        StringBuilder sb = new StringBuilder();
-        if (ge >= 0) {
-            sb.append(ge).append("-");
-        }
-        if (lt >= 0) {
-            sb.append(lt);
-        }
-        return sb.toString();
-    }
-
-    @Override
-    public boolean equals(Object obj) {
-        if (!(obj instanceof TimeRange)) {
-            return false;
-        }
-        TimeRange other = (TimeRange) obj;
-        return other.ge == this.ge && other.lt == this.lt;
-    }
-
-    @Override
-    public int hashCode() {
-        final int PRIME = 31;
-        int result = 1;
-        result = PRIME * result + Long.hashCode(ge);
-        result = PRIME * result + Long.hashCode(lt);
-        return result;
-    }
-}

+ 0 - 47
core-metrics/src/main/java/com/qmth/boot/core/metrics/service/MetricsService.java

@@ -1,47 +0,0 @@
-package com.qmth.boot.core.metrics.service;
-
-import com.qmth.boot.core.metrics.model.MetricsResult;
-
-import java.util.List;
-
-/**
- * 统计服务接口
- */
-public interface MetricsService {
-
-    /**
-     * 记录单次统计结果
-     *
-     * @param endpoint
-     * @param status
-     * @param timecost
-     */
-    void record(String endpoint, int status, long timecost);
-
-    /**
-     * 获取某个统计点的统计结果
-     *
-     * @param endpoint
-     * @return
-     */
-    MetricsResult result(String endpoint);
-
-    /**
-     * 获取所有统计点的统计结果
-     *
-     * @return
-     */
-    List<MetricsResult> result();
-
-    /**
-     * 重置某个统计点的统计结果
-     *
-     * @param endpoint
-     */
-    void reset(String endpoint);
-
-    /**
-     * 重置所有统计结果
-     */
-    void reset();
-}

+ 0 - 65
core-metrics/src/main/java/com/qmth/boot/core/metrics/service/impl/MemoryMetricsService.java

@@ -1,65 +0,0 @@
-package com.qmth.boot.core.metrics.service.impl;
-
-import com.qmth.boot.core.metrics.config.MetricsProperties;
-import com.qmth.boot.core.metrics.model.MetricsResult;
-import com.qmth.boot.core.metrics.service.MetricsService;
-
-import javax.annotation.PreDestroy;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class MemoryMetricsService implements MetricsService {
-
-    private Map<String, MetricsRecorder> recorderMap;
-
-    private MetricsProperties metricsProperties;
-
-    public MemoryMetricsService(MetricsProperties metricsProperties) {
-        this.metricsProperties = metricsProperties;
-        this.recorderMap = new HashMap<>();
-    }
-
-    @PreDestroy
-    public void close() {
-        this.recorderMap.clear();
-    }
-
-    @Override
-    public void record(String endpoint, int status, long timecost) {
-        recorderMap.computeIfAbsent(endpoint, key -> new MetricsRecorder(metricsProperties)).record(status, timecost);
-    }
-
-    @Override
-    public MetricsResult result(String endpoint) {
-        MetricsResult result = new MetricsResult();
-        MetricsRecorder recorder = recorderMap.get(endpoint);
-        if (recorder != null) {
-            result = recorder.getResult();
-        }
-        result.setEndpoint(endpoint);
-        return result;
-    }
-
-    @Override
-    public List<MetricsResult> result() {
-        List<MetricsResult> list = new ArrayList<>();
-        for (Map.Entry<String, MetricsRecorder> entry : recorderMap.entrySet()) {
-            MetricsResult result = entry.getValue().getResult();
-            result.setEndpoint(entry.getKey());
-            list.add(result);
-        }
-        return list;
-    }
-
-    @Override
-    public void reset(String endpoint) {
-        recorderMap.remove(endpoint);
-    }
-
-    @Override
-    public void reset() {
-        recorderMap.clear();
-    }
-}

+ 0 - 60
core-metrics/src/main/java/com/qmth/boot/core/metrics/service/impl/MetricsRecorder.java

@@ -1,60 +0,0 @@
-package com.qmth.boot.core.metrics.service.impl;
-
-import com.qmth.boot.core.metrics.config.MetricsProperties;
-import com.qmth.boot.core.metrics.model.MetricsResult;
-import com.qmth.boot.core.metrics.model.TimeRange;
-
-import java.time.Duration;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicLong;
-
-public class MetricsRecorder {
-
-    private Map<Integer, AtomicLong> statusMap;
-
-    private List<TimeCounter> timeList;
-
-    public MetricsRecorder(MetricsProperties properties) {
-        this.statusMap = new HashMap<>();
-        this.timeList = new ArrayList<>();
-        long ge = 0;
-        for (Duration time : properties.getTimeGroup()) {
-            long lt = time.toMillis();
-            this.timeList.add(new TimeCounter(ge, lt));
-            ge = lt;
-        }
-        this.timeList.add(new TimeCounter(ge, -1));
-    }
-
-    public void record(int status, long timecost) {
-        statusMap.computeIfAbsent(status, key -> new AtomicLong(0)).incrementAndGet();
-        for (TimeCounter counter : timeList) {
-            if (counter.accept(timecost)) {
-                break;
-            }
-        }
-    }
-
-    public MetricsResult getResult() {
-        MetricsResult result = new MetricsResult();
-
-        Map<Integer, Long> statusResult = new HashMap<>();
-        for (Map.Entry<Integer, AtomicLong> entry : statusMap.entrySet()) {
-            statusResult.put(entry.getKey(), entry.getValue().longValue());
-        }
-        result.setStatus(statusResult);
-
-        Map<TimeRange, Long> timeResult = new HashMap<>();
-        for (TimeCounter tc : timeList) {
-            timeResult.put(tc.getTimeRage(), tc.count());
-        }
-        result.setTime(timeResult);
-
-        return result;
-    }
-
-}
-

+ 0 - 35
core-metrics/src/main/java/com/qmth/boot/core/metrics/service/impl/TimeCounter.java

@@ -1,35 +0,0 @@
-package com.qmth.boot.core.metrics.service.impl;
-
-import com.qmth.boot.core.metrics.model.TimeRange;
-
-import java.util.concurrent.atomic.AtomicLong;
-
-public class TimeCounter {
-
-    private TimeRange range;
-
-    private AtomicLong count;
-
-    public TimeCounter(long ge, long lt) {
-        this.range = new TimeRange(ge, lt);
-        this.count = new AtomicLong(0);
-    }
-
-    public TimeRange getTimeRage() {
-        return this.range;
-    }
-
-    public boolean accept(long timecost) {
-        if (timecost >= range.getGe() && (range.getLt() < 0 || timecost < range.getLt())) {
-            count.incrementAndGet();
-            return true;
-        } else {
-            return false;
-        }
-    }
-
-    public long count() {
-        return count.get();
-    }
-
-}

+ 0 - 2
core-metrics/src/main/resources/META-INF/spring.factories

@@ -1,2 +0,0 @@
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
-  com.qmth.boot.core.metrics.config.MetricsAutoConfiguration

+ 0 - 49
core-metrics/src/test/java/com/qmth/boot/test/core/metrics/MetricsTest.java

@@ -1,49 +0,0 @@
-package com.qmth.boot.test.core.metrics;
-
-import com.qmth.boot.core.metrics.config.MetricsProperties;
-import com.qmth.boot.core.metrics.model.MetricsResult;
-import com.qmth.boot.core.metrics.model.TimeRange;
-import com.qmth.boot.core.metrics.service.impl.MemoryMetricsService;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import java.util.List;
-
-public class MetricsTest {
-
-    private static MemoryMetricsService service;
-
-    private static MetricsProperties config;
-
-    @BeforeClass
-    public static void prepare() {
-        config = new MetricsProperties();
-        service = new MemoryMetricsService(config);
-    }
-
-    @AfterClass
-    public static void clear() {
-        service.reset();
-    }
-
-    @Test
-    public void testSingleEndpoint() {
-        service.record("/a1", 200, 8);
-        service.record("/a1", 200, 22);
-        service.record("/a1", 200, 130);
-        service.record("/a1", 400, 12);
-        service.record("/a1", 500, 33);
-        service.record("/a1", 401, 330);
-        service.record("/a1", 404, 1209);
-        List<MetricsResult> list = service.result();
-        Assert.assertEquals(1, list.size());
-        MetricsResult result = list.get(0);
-        Assert.assertEquals(5, result.getStatus().size());
-        Assert.assertEquals(3, result.getStatus().get(200).longValue());
-        Assert.assertEquals(3, result.getTime().get(new TimeRange(10, 100)).longValue());
-        Assert.assertEquals(0, result.getTime().get(new TimeRange(10000, -1)).longValue());
-    }
-
-}

+ 19 - 6
pom.xml

@@ -20,7 +20,6 @@
         <module>core-models</module>
         <module>core-concurrent</module>
         <module>core-uid</module>
-        <module>core-metrics</module>
         <module>core-rate-limit</module>
         <module>core-security</module>
         <module>core-logging</module>
@@ -40,6 +39,7 @@
         <maven.compiler.target>1.8</maven.compiler.target>
         <springboot.version>2.3.7.RELEASE</springboot.version>
         <okhttp.version>3.14.9</okhttp.version>
+        <io.micrometer.version>1.10.4</io.micrometer.version>
     </properties>
 
     <dependencyManagement>
@@ -80,11 +80,6 @@
                 <artifactId>core-uid</artifactId>
                 <version>${project.version}</version>
             </dependency>
-            <dependency>
-                <groupId>com.qmth.boot</groupId>
-                <artifactId>core-metrics</artifactId>
-                <version>${project.version}</version>
-            </dependency>
             <dependency>
                 <groupId>com.qmth.boot</groupId>
                 <artifactId>core-rate-limit</artifactId>
@@ -196,6 +191,24 @@
                 <artifactId>spring-boot-starter-test</artifactId>
                 <version>${springboot.version}</version>
             </dependency>
+            <!-- spring-boot-actuator依赖 -->
+            <dependency>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-starter-actuator</artifactId>
+                <version>${springboot.version}</version>
+            </dependency>
+            <!-- micrometer-core依赖 -->
+            <dependency>
+                <groupId>io.micrometer</groupId>
+                <artifactId>micrometer-core</artifactId>
+                <version>${io.micrometer.version}</version>
+            </dependency>
+            <!-- micrometer-prometheus依赖 -->
+            <dependency>
+                <groupId>io.micrometer</groupId>
+                <artifactId>micrometer-registry-prometheus</artifactId>
+                <version>${io.micrometer.version}</version>
+            </dependency>
             <!-- thirdpart modules -->
             <dependency>
                 <groupId>org.apache.commons</groupId>

+ 8 - 4
starter-api/pom.xml

@@ -28,10 +28,6 @@
             <groupId>com.qmth.boot</groupId>
             <artifactId>tools-common</artifactId>
         </dependency>
-        <dependency>
-            <groupId>com.qmth.boot</groupId>
-            <artifactId>core-metrics</artifactId>
-        </dependency>
         <dependency>
             <groupId>com.qmth.boot</groupId>
             <artifactId>core-rate-limit</artifactId>
@@ -48,6 +44,14 @@
             <groupId>com.qmth.boot</groupId>
             <artifactId>core-models</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-actuator</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>io.micrometer</groupId>
+            <artifactId>micrometer-registry-prometheus</artifactId>
+        </dependency>
         <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>

+ 0 - 7
starter-api/src/main/java/com/qmth/boot/api/annotation/Aac.java

@@ -64,13 +64,6 @@ public @interface Aac {
      */
     SignatureType[] signType() default {};
 
-    /**
-     * 是否统计接口状态
-     *
-     * @return
-     */
-    BOOL metrics() default BOOL.NULL;
-
     /**
      * 接口定义需要的权限
      *

+ 0 - 13
starter-api/src/main/java/com/qmth/boot/api/config/AacConfig.java

@@ -34,11 +34,8 @@ public class AacConfig {
 
     private SignatureType[] signType = EMPTY_SIGNATURE_TYPE;
 
-    private Boolean metrics;
-
     public AacConfig(ApiProperties properties) {
         this.strict = properties.isGlobalStrict();
-        this.metrics = true;
         this.auth = properties.isGlobalAuth();
 
         buildRateLimit(properties.getGlobalRateLimit());
@@ -57,9 +54,6 @@ public class AacConfig {
         if (annotation.auth() != BOOL.NULL) {
             this.auth = (annotation.auth() == BOOL.TRUE);
         }
-        if (annotation.metrics() != BOOL.NULL) {
-            this.metrics = (annotation.metrics() == BOOL.TRUE);
-        }
         if (annotation.ipAllow().length > 0) {
             this.ipAllow = annotation.ipAllow();
         }
@@ -86,9 +80,6 @@ public class AacConfig {
         if (config.auth != null) {
             this.auth = config.auth;
         }
-        if (config.metrics != null) {
-            this.metrics = config.metrics;
-        }
         if (ArrayUtils.isNotEmpty(config.ipAllow)) {
             this.ipAllow = config.ipAllow;
         }
@@ -131,10 +122,6 @@ public class AacConfig {
         return signType;
     }
 
-    public boolean isMetrics() {
-        return metrics;
-    }
-
     private void buildRateLimit(String[] expressions) {
         if (ArrayUtils.isNotEmpty(expressions)) {
             List<RateLimitRule> list = new ArrayList<>(expressions.length);

+ 0 - 2
starter-api/src/main/java/com/qmth/boot/api/constant/ApiConstant.java

@@ -10,8 +10,6 @@ public interface ApiConstant {
 
     String CONFIG_PREFIX = CoreConstant.CONFIG_PREFIX + ".api";
 
-    String CONFIG_METRICS_ENDPOINT = "metrics-endpoint";
-
     String IP_UNKNOWN = "unknown";
 
     String IP_LOCAL_MACHINE = "0:0:0:0:0:0:0:1";

+ 0 - 20
starter-api/src/main/java/com/qmth/boot/api/interceptor/impl/MetricsInterceptor.java

@@ -1,35 +1,20 @@
 package com.qmth.boot.api.interceptor.impl;
 
-import com.qmth.boot.api.config.AacConfig;
-import com.qmth.boot.api.config.ApiConfigService;
-import com.qmth.boot.api.config.ApiProperties;
 import com.qmth.boot.api.constant.ApiConstant;
 import com.qmth.boot.api.interceptor.AbstractInterceptor;
 import com.qmth.boot.api.utils.RequestUtil;
 import com.qmth.boot.core.logger.constant.LoggerConstant;
-import com.qmth.boot.core.metrics.service.MetricsService;
 import com.qmth.boot.tools.uuid.FastUUID;
 import org.apache.commons.lang3.StringUtils;
 import org.slf4j.MDC;
-import org.springframework.http.HttpStatus;
 import org.springframework.stereotype.Component;
 
-import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 @Component
 public class MetricsInterceptor extends AbstractInterceptor implements ApiConstant, LoggerConstant {
 
-    @Resource
-    private ApiProperties apiProperties;
-
-    @Resource
-    private ApiConfigService apiConfigService;
-
-    @Resource
-    private MetricsService metricsService;
-
     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
         // 优先从header读取traceId,否则自动生成
@@ -47,12 +32,7 @@ public class MetricsInterceptor extends AbstractInterceptor implements ApiConsta
     @Override
     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
             Exception ex) {
-        AacConfig config = getAacConfig(apiProperties, apiConfigService, request, handler);
         long timecost = getTimecost(request);
-        // 接口开启统计且响应不为404时,提交记录
-        if (config.isMetrics() && response.getStatus() != HttpStatus.NOT_FOUND.value()) {
-            metricsService.record(request.getServletPath(), response.getStatus(), timecost);
-        }
         // 记录日志
         MDC.put(MDC_CALLER, RequestUtil.getAttribute(request, ATTRIBUTE_CALLER, "-"));
         log.info("{} {} {} {}ms", request.getMethod().toUpperCase(), request.getServletPath(), response.getStatus(),

+ 0 - 30
starter-api/src/main/java/com/qmth/boot/api/metrics/MetricsController.java

@@ -1,30 +0,0 @@
-package com.qmth.boot.api.metrics;
-
-import com.qmth.boot.api.annotation.Aac;
-import com.qmth.boot.api.annotation.BOOL;
-import com.qmth.boot.api.constant.ApiConstant;
-import com.qmth.boot.core.metrics.service.MetricsService;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
-
-import javax.annotation.Resource;
-
-@RestController
-@ConditionalOnProperty(prefix = ApiConstant.CONFIG_PREFIX, name = ApiConstant.CONFIG_METRICS_ENDPOINT)
-@RequestMapping("${" + ApiConstant.CONFIG_PREFIX + ".uri-prefix:" + ApiConstant.DEFAULT_URI_PREFIX + "}${"
-        + ApiConstant.CONFIG_PREFIX + "." + ApiConstant.CONFIG_METRICS_ENDPOINT + "}")
-@Aac(strict = BOOL.FALSE, auth = BOOL.FALSE, rateLimit = "5/1s", metrics = BOOL.FALSE, ipAllow = { "192.168.*.*",
-        "172.16.*.*" })
-public class MetricsController {
-
-    @Resource
-    private MetricsService metricsService;
-
-    @RequestMapping
-    public Object index(@RequestParam(required = false) String endpoint) {
-        return endpoint != null ? metricsService.result(endpoint) : metricsService.result();
-    }
-
-}