1

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

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

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

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

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

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

4

1 回答 1

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; }

If you want to be fancy, put the notifications onto a JMS queue and use its infrastructure to listen for new items and process them.

于 2011-12-27T16:19:11.213 回答