【发布时间】:2018-01-13 11:55:04
【问题描述】:
计算一个 API 在 Spring Boot 中触发成功/失败响应的次数的最佳方法是什么。
我的想法是在应用程序启动和调用 api 时使用 post 构造启动一个新线程,然后为每个新的唯一请求使用计数器服务来计算有多少 api 被触发该特定请求以及其中有多少成功或失败。
如果你们有的话,推荐一些新的方法。
【问题讨论】:
标签: java spring rest spring-boot performancecounter
计算一个 API 在 Spring Boot 中触发成功/失败响应的次数的最佳方法是什么。
我的想法是在应用程序启动和调用 api 时使用 post 构造启动一个新线程,然后为每个新的唯一请求使用计数器服务来计算有多少 api 被触发该特定请求以及其中有多少成功或失败。
如果你们有的话,推荐一些新的方法。
【问题讨论】:
标签: java spring rest spring-boot performancecounter
您不必从头开始创建,您可以简单地使用内置此功能的 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 如果你使用那个。
【讨论】: