java - Spring Boot 中 Rest Api 的计数器指标

标签 java spring rest spring-boot performancecounter

在 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/

相关文章:

php - REST API——Javascript 还是 PHP?

java - 为什么使用克隆进行防御性复制会带来安全问题?

java - 如何命名显示属性存在的接口(interface)?

java - Jersey WebApplicationException 和 servlet 过滤器

java - 如何获取 ANTLRs java 运行时中所有出现的解析器规则?

java - 收到http错误后如何在Spring Integration中访问自定义 header

java - 使用 Spring HATEOAS 构建模板化搜索资源 uri

java - Spring Security + AngularJS Ajax 帖子

rest - Angular 2 创建模型与动态处理 json 对象?

java - 在 Angular 4 中将数据发送到 JAVA post REST API 时出现 CORS 错误