【问题标题】:Java server framework to listen to PostgreSQL NOTIFY statements用于侦听 PostgreSQL NOTIFY 语句的 Java 服务器框架
【发布时间】:2012-01-27 21:08:06
【问题描述】:

我需要编写一个服务器来侦听 PostgreSQL NOTIFY 语句并将每个通知视为服务请求(实际上,更像是一个要处理的任务)。我的主要要求是:

1) 轮询PGConnection 的机制(理想情况下,这将是一个侦听器,但在 PgJDBC 实现中,我们需要轮询挂起的通知。Reference

2) 在单独的线程上执行基于“请求”的回调(使用 NOTIFY 通知中的通道名称)。

3) 内置线程管理功能。(在处理/完成任务时创建/删除线程,在同时处理太多任务时放入队列等)

要求 1 和 2 对我来说很容易实现。但是我不想自己写线程管理。

是否存在满足此要求的现有框架?如果框架自动生成请求统计信息,则另一个优势是。

【问题讨论】:

    标签: postgresql notify


    【解决方案1】:

    说实话,只需使用 Executors 的标准 ExecutorService 实现就可以轻松满足要求 3,例如,这将允许您获取固定大小的线程池并以 Runnable 或 Callable 的形式向它们提交工作实施。他们将处理创建线程到限制等的血腥细节。然后您可以让您的侦听器实现一个薄层 Runnable 来收集统计信息等。

    类似:

    private final ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    private final NotificationCallback callback;
    private int waiting, executing, succeeded, failed;
    
    public void pollAndDispatch() {
       Notification notification;
       while ((notification = pollDatabase()) != null) {
          final Notification ourNotification = notification;
          incrementWaitingCount();
          threadPool.submit(new Runnable() {
             public void run() {
               waitingToExecuting();
               try {
                 callback.processNotification(ourNotification);
                 executionCompleted();
               } catch (Exception e) {
                 executionFailed();
                 LOG.error("Exeception thrown while processing notification: " + ourNotification, e);
               }
             }
          });
       }
    }
    // check PGconn for notification and return it, or null if none received
    protected Notification pollDatabase() { ... }
    // maintain statistics
    private synchronized void incrementWaitingCount() { ++waiting; }
    private synchronized void waitingToExecuting() { --waiting; ++executing; }
    private synchronized void executionCompleted() { --executing; ++succeeded; }
    private synchronized void executionFailed() { --executing; ++failed; }
    

    如果您想花点心思,可以将通知放到 JMS 队列中,并使用其基础架构来侦听和处理新项目。

    【讨论】:

    • 我环顾四周,自己写它看起来是个好主意。感谢您的回复,代码 sn-p 真的很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 2021-10-11
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多