点击蓝色“陈树义”关注我哟
上篇文章我们已经可以在 Grafana 上看到对应的 SpringBoot 应用信息了,通过这些信息我们可以对 SpringBoot 应用有更全面的监控。但是如果我们需要对一些业务指标做监控,我们应该怎么做呢?这篇文章就带你一步步实现一个模拟的订单业务指标监控。
假设我们有一个订单系统,我们需要监控它的实时订单总额、10 分钟内的下单失败率、请求失败数。那么我们应该怎么做呢?
添加业务监控指标
在 spring-web-prometheus-demo 项目的基础上,我们添加一个 PrometheusCustomMonitor 类。在这里面我们定义了三个业务指标:
order_request_count:下单总次数
order_amount_sum:下单总金额
@Component
public class PrometheusCustomMonitor {
/**
* 订单发起次数
*/
private Counter orderCount;
/**
* 金额统计
*/
private DistributionSummary amountSum;
private final MeterRegistry registry;
@Autowired
public PrometheusCustomMonitor(MeterRegistry registry) {
this.registry = registry;
}
@PostConstruct
private void init() {
orderCount = registry.counter("order_request_count", "order", "test-svc");
amountSum = registry.summary("order_amount_sum", "orderAmount", "test-svc");
}
public Counter getOrderCount() {
return orderCount;
}
public DistributionSummary getAmountSum() {
return amountSum;
}
}
模拟订单数据
这里我们新增一个 TestController 类,去模拟现实的订单数据。
后续应用启动后,我们可以通过 localhost:8080/order 去模拟用户下单操作。
package com.chenshuyi.springwebprometheusdemo;
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;
import java.util.Random;
@RestController
public class TestController {
@Resource
private PrometheusCustomMonitor monitor;
@RequestMapping("/order")
public String order() throws Exception {
// 统计下单次数
monitor.getOrderCount().increment();
Random random = new Random();
int amount = random.nextInt(100);
// 统计金额
monitor.getAmountSum().record(amount);
return "下单成功, 金额: " + amount;
}
}