2011-12-26 53 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