在 spring boot 中计算 API 被触发成功/失败响应的次数的最佳方法是什么。
我的想法是在应用程序启动时和调用 api 时使用 post 构造启动新线程,然后为每个新的唯一请求使用计数器服务来计算有多少 api 被触发该特定请求以及其中有多少成功或失败。
如果你们有新的方法,推荐一些。
最佳答案
您不必从头开始创建,您可以简单地使用内置此功能的 Spring Boot Actuator。只需将以下依赖项添加到您的项目中:
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
执行器暴露,例如/metrics
端点,在这里您可以找到所有响应的计数器 - 每个计数器都以 counter.status.{{status_code}}.{{endpoint}}
开头。
例如,我有一个带有 /hello
端点的简单演示应用程序。任何时候我调用这个端点指标 counter.status.200.hello
都会增加。当我访问 /metrics
端点时,我可以看到类似以下内容:
{
"mem": 586013,
"mem.free": 324496,
"processors": 8,
"instance.uptime": 144496,
"uptime": 149950,
"systemload.average": 0.52,
"heap.committed": 522240,
"heap.init": 251904,
"heap.used": 197743,
"heap": 3580928,
"nonheap.committed": 64960,
"nonheap.init": 2496,
"nonheap.used": 63773,
"nonheap": 0,
"threads.peak": 42,
"threads.daemon": 25,
"threads.totalStarted": 54,
"threads": 27,
"classes": 8938,
"classes.loaded": 8938,
"classes.unloaded": 0,
"gc.ps_scavenge.count": 8,
"gc.ps_scavenge.time": 54,
"gc.ps_marksweep.count": 2,
"gc.ps_marksweep.time": 65,
"gauge.response.star-star.favicon.ico": 1,
"counter.status.200.star-star": 2,
"counter.status.304.star-star": 2,
"counter.status.200.metrics.name": 2,
"counter.status.200.star-star.favicon.ico": 5,
"gauge.response.star-star": 3,
"gauge.response.hello": 5,
"gauge.response.metrics.name": 3,
"counter.status.200.hello": 2,
"counter.status.404.metrics.name": 1,
"httpsessions.max": -1,
"httpsessions.active": 0,
"datasource.primary.active": 0,
"datasource.primary.usage": 0
}
我还可以访问单个指标,例如/metrics/counter.status.200.hello
仅返回:
{
"counter.status.200.hello": 2
}
默认情况下 /metrics
端点是安全的。对于您的本地开发人员,您可以通过添加以下内容来关闭它:
management:
security:
enabled: false
到您的application.yml 或
management.security.enabled=false
application.properties 如果您使用那个。
关于java - Spring Boot 中 Rest Api 的计数器指标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48239614/