如何对来自 Java CDI EVENT 的观察数据进行分组以延迟发送?

发布于 2025-01-13 00:42:34 字数 618 浏览 4 评论 0原文

我们正在开发一项功能,希望从后端观察事件并将它们传播到外部服务。问题是,有时这些事件快速连续发生并导致性能问题。

我们将 Java 8 与 JavaEE 7 结合使用,更具体地说,我们在 @ApplicationScoped CDI 类中使用事件功能。我们当前实现它的方式如下(该线程的代码被精简为准系统):

@ApplicationScoped
public class DataObserver {

    public void observeData(@Observes Data data) {
        pushForward(data);
    }

    ...
}

现在的目标是将多个请求分组在一起,并在必要时稍微延迟地发送它们。我们可以执行 1 个请求,每个请求包含 10 个数据,而不是每个请求包含 10 个数据。

此外,我们也不想等待 10 个对象累积完毕。数据应该每隔几秒转发一次,无论当时积累了多少数据对象。这是我们正在努力解决的部分,因为我想不出正确的解决方案。

有没有一种干净的方法可以保证我不会丢失任何数据?也许使用池大小为 1 的 ScheduledExecutorService 并延迟提交任务,同时还添加一个额外的任务以确保安全?

将不胜感激的帮助。

We are working on a feature where we want to observe events from our backend and propagate them forward to an external service. The issue is that sometimes these events come in rapid succession and cause performance issues.

We use Java 8 with JavaEE 7, more specifically we use the Event feature in an @ApplicationScoped CDI class. The current way we have it implemented is the following (code was trimmed to barebones for this thread):

@ApplicationScoped
public class DataObserver {

    public void observeData(@Observes Data data) {
        pushForward(data);
    }

    ...
}

The goal now is to group multiple requests together and send them with a tiny bit of delay, if necessary. Instead of 10 request with Data each, we could do 1 request with 10 Data each.

Additionally we don't want to wait for 10 objects to accumulate either. Data should be forwarded every few seconds regardless of how many Data objects were accumulated by then. This is the part we are struggling with, since I cannot think of the proper solution.

Is there a clean way of doing this that guarantees me that no data will be missed? Maybe use ScheduledExecutorService with pool size 1 and submit tasks with a delay, while also adding an additional task for safety?

Would appreciate the help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文