我有一个 Spring Boot 应用程序,必须使用自定义代码发送分析数据。 我不希望每次收到记录时都发送数据,而是缓冲它们并以批量 X 元素发送它们。 例如,如果批量大小为 10,而我在 2 分钟内只收到 5 个,我需要发送所有这些并重新开始。
我使用术语“缓冲区”是因为我没有找到更好的方法来描述它。 实现这样的事情的最佳方法是什么?是否有现有的 API 可以实现相同的功能?
最佳答案
您可以使用CountDownLatch
.
public class Sender implements Runnable {
public CountDownLatch recordCount;
public sender(CountDownLatch recordCount) {
this.recordCount = recordCount;
}
public void run() {
recordCount.await(2, TimeUnit.MINUTES); // this will stop waiting after 2 minutes or countDown is complete
//send records in buffer
}
}
public class Receiver implements Runnable {
public CountDownLatch recordCount;
public receiver(CountDownLatch recordCount) {
this.recordCount = recordCount;
}
public void run() {
//recieve and add to buffer
recordCount.countDown(); // this will deceremnt the count
}
}
关于java - 我有很多分析调用要发送,如果缓冲区未满,如何缓冲它们并在一定时间内刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61678192/