如何计算springboot中某个端点的吞吐量?

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

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

任何人都可以提供吞吐量计算的逻辑以及最好的方法吗?

java spring-boot throughput
1个回答
0
投票

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

如果您只对计算 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.