2011-12-26 52 views
1

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

1)机制,就PGConnection轮询(理想情况下,这将是一个倾听者,但在PgJDBC实现,我们需要轮询未处理通知Reference

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

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

要求1和2是什么这对我来说很容易实现。但我宁愿不自己编写线程管理。

是否有满足此要求的现有框架?如果框架自动生成请求统计信息,则会带来额外的好处。

回答

1

说实话,要求3可能很容易被使用,只需使用Executor的标准ExecutorService实现,例如,您可以获得一个固定大小的线程池并以Runnable的形式向他们提交工作或可调用的实现。他们将讨论创建线程到了极限等的血淋淋的细节..然后,您可以有你的听众实现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队列中,并使用其基础结构来监听新项目并处理它们。

+0

我环顾四周,自己写这看起来像个好主意。感谢您的回复,并且代码段非常有帮助。 – Aman 2011-12-29 09:20:16