事件觸發、分發、observer機制—-訊息匯流排架構模式(中介者(調停者)設計模式)

來源:互聯網
上載者:User

傳統的observer(事件-監聽)機制一般使用 比較直觀的一種是使用一種“註冊——通知——撤銷註冊”的形式。但是這種形式可以通過一個純被觀察對象的純虛介面類實現依賴倒置實現解耦,但是事實還是有一定的耦合,比如對象的生存周期就通過註冊和撤銷註冊耦合了。

前言

一直以來,都對非同步事件高度興趣,比如一個應用在運行一個耗時的過程時,最好的方式是提交這個耗時的過程給一個專門的背景工作執行緒,然後立即返回到主線程上,進行其他的任務,而背景工作執行緒完成耗時任務後,非同步通知主線程,這個過程本身是很有意思的。傳統的事件-監聽器模型可以較好的解決這個問題,不過事件監聽器兩者的耦合往往略顯緊密,所以需要另一種實現,使得這兩者的耦合盡量小,那樣模組可以比較通用。

匯流排模式

前幾天跟同事討論了下Swing中的訊息機制,同事給我講了下匯流排模式的訊息機制,感覺很有意思,於是周末就自己實現了下。具體的思路是這樣的:

  • 系統中存在一個Message Service(Message Service),即匯流排
  • 監聽器對象,通過實現一個可被通知的對象的介面,將自己註冊在Message Service上
  • 可被通知的對象可以向訊息匯流排上post訊息,就這個對象而言,它對其他註冊在匯流排上的對象是一無所知的
  • Message Service進行訊息的調度和轉寄,將訊息(事件)發送給指定的對象,從而傳遞這個非同步事件

這個思路最大的好處是,事件被抽象成訊息(Message),具有統一的格式,便於傳遞。掛在匯流排上的監聽器互相不知道對方的存在,監聽器可以指定自己感興趣的訊息類型,訊息可以是廣播的形式,也可以是點對點的。(後來參看了下JMS,其中有pub/sub的模式(即訂閱模式),不過,對於非同步訊息的傳遞來說,這個可以不必實現)

Message Service

Message Service可以將一大堆分布在不同物理機上的應用整合起來,進行通訊,可以將一些小的應用整合為一個大的,可用的應用系統

用一個例子來說吧:

原始碼複製列印
  1. public class Test{  
  2.     public static void main(String[] args) throws RemoteException{  
  3.         /* 
  4.          * 建立一個可被通知的對象(監聽器), 這個監聽器關注這樣幾個事件 
  5.          * TIMEOUT, CLOSE, and READY 
  6.          */  
  7.         Configuration config = new RMIServerConfiguration(null, 0);  
  8.         CommonNotifiableEntry entry1 =   
  9.             new CommonNotifiableEntry(config, "client1",   
  10.                 MessageTypes.MESSAGE_TIMEOUT |   
  11.                 MessageTypes.MESSAGE_CLOSE |   
  12.                 MessageTypes.MESSAGE_READY);  
  13.           
  14.         /* 
  15.          * 建立另一個監聽器, 這個監聽器關注這樣幾個事件 
  16.          * OPEN, CLOSE, and TIMEOUT. 
  17.          */  
  18.         CommonNotifiableEntry entry2 =   
  19.             new CommonNotifiableEntry(config, "client2",   
  20.                 MessageTypes.MESSAGE_OPEN |   
  21.                 MessageTypes.MESSAGE_CLOSE |   
  22.                 MessageTypes.MESSAGE_TIMEOUT);  
  23.           
  24.         // 將監聽器掛在BUS上  
  25.         entry1.register();  
  26.         entry2.register();  
  27.           
  28.         // 建立一個新的訊息, MESSAGE_OPEN類型.  
  29.         Message msg = new CommonMessage(  
  30.                 entry1.getId(),  
  31.                 entry2.getId(),  
  32.                 MessageTypes.MESSAGE_OPEN,  
  33.                 "busying now");  
  34.           
  35.         // 傳遞給entry2  
  36.         entry1.post(msg);  
  37.           
  38.         // 建立一個MESSAGE_CLICKED類型的訊息, entry2  
  39.         // 不關注這個類型的訊息,所以此訊息不會被傳遞  
  40.         Message msgCannotBeReceived = new CommonMessage(  
  41.                 entry1.getId(),  
  42.                 entry2.getId(),  
  43.                 MessageTypes.MESSAGE_CLICKED,  
  44.                 "cliked evnet");  
  45.         entry1.post(msgCannotBeReceived);  
  46.           
  47.         try {  
  48.             Thread.sleep(2000);  
  49.         } catch (InterruptedException e) {  
  50.             e.printStackTrace();  
  51.         }  
  52.           
  53.         // re use the message object to send another message entry  
  54.         msg.setSource(entry2.getId());  
  55.         msg.setTarget(entry1.getId());  
  56.         msg.setType(MessageTypes.MESSAGE_READY);  
  57.         msg.setBody("okay now");  
  58.         entry2.post(msg);  
  59.           
  60.         // 卸載這些監聽器,當程式退出,或者  
  61.         // 或者監聽器不在關注事件發生的時候  
  62.         entry1.unregister();  
  63.         entry2.unregister();  
  64.     }  
  65. }  

 

當前,這個系統可以支援遠端訊息傳遞(通過java的RMI機制),不過對於定址方面還沒有做進一步的處理,有時間再來完善吧。

Message Service的實現

下面我把Message Service的主要實現部分貼出來分析一下:

原始碼複製列印
  1. /** 
  2.  *  
  3.  * @author Abruzzi 
  4.  * 
  5.  */  
  6. public class MessageBus extends UnicastRemoteObject implements Bus{  
  7.     private static MessageBus instance;  
  8.     private List<NotifiableEntry> listeners;  
  9.     private List<Message> messages;  
  10.     private Thread daemonThread = null;  
  11.       
  12.     public static MessageBus getInstance() throws RemoteException{  
  13.         if(instance == null){  
  14.             instance = new MessageBus();  
  15.         }  
  16.         return instance;  
  17.     }  
  18.       
  19.     private MessageBus() throws RemoteException{  
  20.         listeners = new LinkedList<NotifiableEntry>();  
  21.         messages = new LinkedList<Message>();  
  22.         Daemon daemon = new Daemon();  
  23.         daemonThread = new Thread(daemon);  
  24.         daemonThread.setPriority(Thread.NORM_PRIORITY + 3);  
  25.         daemonThread.setDaemon(true);  
  26.         daemonThread.start();  
  27.           
  28.         while(!daemonThread.isAlive());  
  29.     }  
  30.       
  31.     /** 
  32.      * mount notifiable object to listener list 
  33.      */  
  34.     public void mount(NotifiableEntry entry) throws RemoteException{  
  35.         synchronized(listeners){  
  36.             listeners.add(entry);  
  37.             listeners.notifyAll();  
  38.         }  
  39.     }  
  40.   
  41.     /** 
  42.      * unmount the special notifiable object from listener 
  43.      */  
  44.     public void unmount(NotifiableEntry entry) throws RemoteException{  
  45.         synchronized(listeners){  
  46.             listeners.remove(entry);  
  47.             listeners.notifyAll();  
  48.         }  
  49.     }  
  50.       
  51.     /** 
  52.      * post a new message into the bus 
  53.      * @param message 
  54.      */  
  55.     public void post(Message message) throws RemoteException{  
  56.         synchronized(messages){  
  57.             messages.add(message);  
  58.             messages.notifyAll();  
  59.         }  
  60.     }  
  61.       
  62.     /** 
  63.      *  
  64.      * @author Abruzzi 
  65.      * worker thread, dispatch message to appropriate listener 
  66.      * 
  67.      */  
  68.     private class Daemon implements Runnable{  
  69.         private boolean loop = true;  
  70.         public void run(){  
  71.             while(loop){  
  72.                 if(messages.size() == 0){  
  73.                     synchronized(messages){  
  74.                         try {messages.wait();}   
  75.                         catch (InterruptedException e) {  
  76.                             e.printStackTrace();  
  77.                         }  
  78.                     }  
  79.                 }  
  80.                 processIncomingMessage();  
  81.             }  
  82.         }  
  83.     }  
  84.       
  85.     /** 
  86.      * process the incoming message, remove the first message from 
  87.      * queue, and then check all listeners to see whether should  
  88.      * deliver the message to or not. 
  89.      */  
  90.     private void processIncomingMessage(){  
  91.         Message msg;  
  92.         synchronized(messages){  
  93.             msg = messages.remove(0);  
  94.         }  
  95.         String target = null;  
  96.         int type = 0;  
  97.         int mask = 0;  
  98.         try {  
  99.             target = msg.getTarget();  
  100.             type = msg.getType();  
  101.             if(target == MessageTypes.SENDTOALL){  
  102.                 for(NotifiableEntry entry : listeners){  
  103.                     mask = entry.getSense();  
  104.                     if((mask & type) == type){entry.update(msg);}  
  105.                 }  
  106.             }else{  
  107.                 for(NotifiableEntry entry : listeners){  
  108.                     mask = entry.getSense();  
  109.                     if(entry.getId().equals(target) && (mask & type) == type){  
  110.                         entry.update(msg);  
  111.                     }  
  112.                 }  
  113.             }  
  114.         } catch (RemoteException e) {  
  115.             e.printStackTrace();  
  116.         }  
  117.     }  
  118.   
  119. }  

訊息匯流排是一個RMI對象,其中mount(), unmout(), post()等方法可以被遠程調用。MessageBus維護兩個列表,一個訊息列表,一個監聽器列表。當訊息被post到匯流排上後,post會立即返回,然後背景工作執行緒啟動,取出訊息並將其分發到合適的監聽器上。

可能,對同步的處理上考慮不夠周全,下來再繼續修改。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.