Spring Boot:我怎样才能等到在表中获得一条记录并根据它进行一些处理?

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

问题:外部API在Kafka主题中发送一个事件,当我收到该事件时,我将其插入表中。同时前端调用我自己的API(/execute),我需要根据事件做一些处理。

建议的解决方案:从后端,我需要轮询或等待,直到将记录插入表中,一旦收到它,我将进行处理。所以我必须每隔 5 秒左右检查一次数据库,如果我得到记录,我将继续处理。检查这一点的最大窗口约为 2 分钟(FE 将被阻止直到此时)。如果我在 2 分钟内没有得到记录,我必须返回一些错误。

我的实现:

public void startTask() {
        System.out.println("Task started...");

        long startTime = System.currentTimeMillis();
        long duration = 50000; // 50 seconds

        while (System.currentTimeMillis() - startTime < duration) {
            // Task logic here - to get the record from DB
            System.out.println("Running task at " + (System.currentTimeMillis() - startTime) / 1000 + " seconds.");

            try {
                Thread.sleep(5000); // Wait for 5 seconds before the next iteration
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("Task interrupted!");
                break;
            }
        }

        System.out.println("Task finished after 50 seconds.");
    }

有没有更好的方法来继续这个问题?我不喜欢在代码中使用 Thread.sleep 。我认为最好公开一个 GET API (/checkStatus),FE 可以使用它来检查数据库记录的状态,如果找到记录,那么 FE 可以点击 /execute API 进行处理.

请提出更好的方法,以便我可以学习并说服我的架构师!

spring database postgresql spring-boot polling
1个回答
0
投票

您可以使用 PostgreSQL 的

LISTEN
NOTIFY
来代替定期轮询,以实现不同会话之间的进程间通信。 请参阅此处,了解如何使用 psycopg2
LISTEN
的说明。要在插入行时让数据库
NOTIFY
成为侦听器,您可以使用数据库触发器。请注意,仅在事务提交时才会发送通知。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.