要确定isUniqueValue(..) 的结果,您已经存储了使用的值。您可以使用该存储来创建适当的指标。
假设您将每个使用的值存储在一个名为usedIds 的列表中。此外,假设您正在生成一个介于 0 和 1000 之间的唯一数字。
在这种情况下,您可以编写这样的方法:
public float getPercentageUsed() {
return (float) usedIds.size() / 1000;
}
现在您可以创建一个Gauge 来将此值添加到指标中。假设用于生成唯一值的类称为UniqueValueService,它是一个合适的 Spring bean。在这种情况下,您可以像这样创建Gauge bean:
@Bean
public Gauge uniqueValueUsedGauge(MeterRegistry registry, UniqueIdService service) {
return Gauge
.builder("unique-values-used", service::getPercentageUsed)
.baseUnit("%")
.description("Percentage of possible unique values that have been used")
.register(registry);
}
编辑:看来我误解了你的问题。如果您想获得tryToGenerate 的直方图,以查看在第一次、第二次或第 n 次尝试中成功的次数,您可以使用DistributionSummary。例如:
@Bean
public DistributionSummary summary(MeterRegistry registry) {
return DistributionSummary
.builder("unique-value-attempts")
.sla(1, 5, 10)
.publishPercentileHistogram()
.register(registry);
}
在本例中,它将计算在第 1 次、第 5 次或第 10 次尝试中成功调用的次数。
在您的服务中,您现在可以自动连接DistributionSummary,在循环结束时,您可以像这样使用它:
do {
tryToGenerate++
value = generateRandom();
boolean unique = isUniqueValue(value);
} while (!unique);
distributionSummary.record(tryToGenerate); // Add this
现在您可以使用/actuator/metrics/unique-value-attempts.histogram?tag=le:1 查看第一次尝试成功调用的次数。第 5 次和第 10 次尝试也是如此。