gpt4 book ai didi

java - Micrometer - Prometheus Gauge 显示 NaN

转载 作者:搜寻专家 更新时间:2023-11-01 03:16:13 27 4
gpt4 key购买 nike

我正在尝试通过将 Micrometer.io 与 Spring Boot 2.0.0.RELEASE 结合使用来生成 Prometheus 指标。

当我尝试将 List 的大小时公开为 Gauge 时,它​​一直显示 NaN。在文档中它说;

It is your responsibility to hold a strong reference to the state object that you are measuring with a Gauge.

我尝试了一些不同的方法,但我无法解决问题。这是我的一些试验代码。

import io.micrometer.core.instrument.*;
import io.swagger.backend.model.Product;
import io.swagger.backend.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("metrics")
public class ExampleController {

private AtomicInteger atomicInteger = new AtomicInteger();

private ProductService productService;
private final Gauge productGauge;

@Autowired
public HelloController(ProductService productService,
MeterRegistry registry) {

this.productService = productService;

createGauge("product_gauge", productService.getProducts(), registry);
}

private void createGauge(String metricName, List<Product> products,
MeterRegistry registry) {

List<Product> products = productService.getProducts();

// #1
// this displays product_gauge as NaN
AtomicInteger n = registry.gauge("product_gauge", new AtomicInteger(0));
n.set(1);
n.set(2);

// #2
// this also displays product_gauge as NaN
Gauge
.builder("product_gauge", products, List::size)
.register(registry);

// #3
// this displays also NaN
testListReference = Arrays.asList(1, 2);
Gauge
.builder("random_gauge", testListReference, List::size)
.register(registry);

// #4
// this also displays NaN
AtomicInteger currentHttpRequests = registry.gauge("current.http.requests", new AtomicInteger(0));
}

@GetMapping(path = "/product/decrement")
public Counter decrementAndGetProductCounter() {
// decrement the gague by one
}
}

有没有人可以帮助解决这个问题?任何帮助将不胜感激。

最佳答案

在所有情况下,您都必须持有对观察到的实例的强引用。当您的 createGauge() 方法退出时,所有函数堆栈分配的引用都符合垃圾回收条件。

对于 #1,像这样传递您的 atomicInteger 字段:registry.gauge("my_ai", atomicInteger);。然后根据需要递增/递减。每当micrometer需要查询它的时候,只要找到引用它就会查询。

对于 #2,传递您的 productService 字段和一个 lambda。基本上,无论何时查询仪表,它都会使用提供的对象调用该 lambda:registry.gauge("product_gauge", productService, productService -> productService.getProducts().size());

(不保证语法错误。)

关于java - Micrometer - Prometheus Gauge 显示 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50821924/

27 4 0
文章推荐: java.lang.ArrayStoreException : when assigning value with incorrect type to Object[] array 异常
文章推荐: java - 为什么 Collections#shuffle 不使用 ThreadLocalRandom?
文章推荐: java - Oracle 的 Collection 教程令人困惑