如果我有一个 HTTP REST API:example/getCount
示例代码
@RestController
public class CountController {
long count = 0;
@Getmapping("/getCount")
public long getCount(){
count++; // Here is the problem, how to keep the latest count if the API was hit by multiple Application/clients
return count;
}
}
问题描述:任何应用程序/系统每次调用上述API时,计数都会加1,调用方实体可以得到准确的命中数。
条件:它是一个开放的 API。需要指导如何实现它。 这是我遇到的唯一问题陈述
最佳答案
如果你想要计数器行为如下,你可以使用静态类型
- 计数器对于所有调用 API 的客户端都是通用的。
- 一旦服务器重启,计数器就会重新归零。
@RestController
public class CountController {
static long count = 0;
@Getmapping("/getCount")
public long getCount(){
count++; // Here is the problem, how to keep the latest count if the API was hit by multiple Application/clients
return count;
}
}
如果您希望所有客户端使用不同的计数器,或者即使服务器关闭或重启也希望保留计数器值,那么您需要使用数据库来存储计数器。
关于java - 调用 REST API 的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59587909/