如何计算Spring Boot中端点的吞吐量?

问题描述 投票:0回答:2

我正在尝试计算http端点的吞吐量。首先,我们需要端点的 http 请求数。当服务器重新启动时,我是否也需要存储计算出的计数?

如何制定吞吐量计算逻辑以及最佳的执行方式?

java spring-boot throughput
2个回答
2
投票

如果您能够使用其他 Spring 库,我建议您查看 sprint-boot-actuator

implementation 'org.springframework.boot:spring-boot-starter-actuator'

application.yaml

management:
  server:
   port: 9090
  endpoints:
   web:
     exposure:
     include: health, metrics, prometheus

然后服务器将以一种可由 Prometheus 服务器(如 Grafana)抓取的格式公开指标。

可以通过 prometheus 格式的 url

http://localhost:9090/actuator/prometheus
检索。

http://localhost:9090/actuator/metrics
只是为了可观察性。

端点指标将以

http.server.requests
格式提供。

要获取特定指标的 RPS,您应该进行计算

http.server.requests.seconds.sum / http.server.requests.seconds.count

文档中有更多内容。


1
投票

如果您不想为此目的使用其他工具,则有一些可能的情况。

如果您只对计算 HTTP 端点的吞吐量感兴趣并且用户数量不太大,则可以通过将其记录在专用文件中来保存此数字:

 @GetMapping("/endpointName")
public String handleRequest() {
    // Increment the counter for the given endpoint name
    endpointCalls.logAndIncrementCounter(Controller.class.getName(), "endpointName");
    
    // Perform other processing here
    
    return "Request processed successfully";
}

以下逻辑将增加端点调用的计数并重写日志文件。您可以修改此代码以将数据保存在您喜欢的任何位置 - 数据库、缓存或通过其他日志记录方式:

@Component
public class EndpointCalls {

    private static final Logger LOG = LoggerFactory.getLogger(EndpointCalls.class);

    private static Map<String, Integer> counterMap = new HashMap<>();

    public void logAndIncrementCounter(String className,String endpointName) {


        // Increment the counter for the given endpoint name
        counterMap.put(className+"."+endpointName, counterMap.getOrDefault(className+"."+endpointName, 0) + 1);

        // Get the Tomcat base directory
        String catalinaHome = System.getProperty("catalina.home");

        // Construct the log file path
        String logFilePath = catalinaHome + "/logs/endpointCalls.log";

        // Clear the file content and log the new map
        try (PrintWriter writer = new PrintWriter(new FileWriter(logFilePath, false))) {
            writer.print(""); // Clear the file content
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Log the method call
        String mapAsJson = new Gson().toJson(counterMap);
        LOG.debug("Endpoint called: {}", mapAsJson);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.