2011-12-26 7 views
1

PostgreSQLのNOTIFY文をリッスンし、各通知を処理するタスク(実際には処理するタスクのようなもの)とみなすサーバを作成する必要があります。私の主な要件は次のとおりです。PostgreSQLのNOTIFY文を聞くためのJavaサーバフレームワーク

1)(理想的には、これはリスナーになりますが、PgJDBCの実装では、我々は、保留中の通知をポーリングするために必要とされているPGConnectionにポーリングするメカニズムReference

2)を実行します。別のスレッド上の "要求"(NOTIFY通知のチャネル名を使用)に基づくコールバック

3)に建てられたスレッド管理のものを持っています。(スレッドを作成/削除するタスクは、あまりにも多くのタスクを同時に処理されているとき

要件1と2が何かしている)などがキューに入れ、完成/処理されたとき私は自分自身を実装するのは簡単です。しかし私は自分自身でスレッド管理を書かない方がよいでしょう。

この要件を満たす既存のフレームワークはありますか?追加の利点は、フレームワークが要求統計を自動的に生成する場合です。

答えて

1

実際には、Executorsの標準ExecutorService実装を使用するだけで要件3を簡単に満たすことができます。たとえば、固定サイズのスレッドプールを取得して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

関連する問題