现在的位置: 首页 > 综合 > 正文

事件触发、分发、observer机制—-消息总线架构模式(中介者(调停者)设计模式)

2013年09月01日 ⁄ 综合 ⁄ 共 6658字 ⁄ 字号 评论关闭

传统的observer(事件-监听)机制一般使用 比较直观的一种是使用一种“注册——通知——撤销注册”的形式。但是这种形式可以通过一个纯被观察对象的纯虚接口类实现依赖倒置实现解耦,但是事实还是有一定的耦合,比如对象的生存周期就通过注册和撤销注册耦合了。

前言

一直以来,都对异步事件很感兴趣,比如一个应用在运行一个耗时的过程时,最好的方式是提交这个耗时的过程给一个专门的工作线程,然后立即返回到主线程上,进行其他的任务,而工作线程完成耗时任务后,异步的通知主线程,这个过程本身是很有意思的。传统的事件-监听器模型可以较好的解决这个问题,不过事件监听器两者的耦合往往略显紧密,所以需要另一种实现,使得这两者的耦合尽量小,那样模块可以比较通用。

总线模式

前几天跟同事讨论了下Swing中的消息机制,同事给我讲了下总线模式的消息机制,感觉很有意思,于是周末就自己实现了下。具体的思路是这样的:

  • 系统中存在一个消息服务(Message Service),即总线
  • 监听器对象,通过实现一个可被通知的对象的接口,将自己注册在消息服务上
  • 可被通知的对象可以向消息总线上post消息,就这个对象而言,它对其他注册在总线上的对象是一无所知的
  • 消息服务进行消息的调度和转发,将消息(事件)发送给指定的对象,从而传递这个异步事件

这个思路最大的好处是,事件被抽象成消息(Message),具有统一的格式,便于传递。挂在总线上的监听器互相不知道对方的存在,监听器可以指定自己感兴趣的消息类型,消息可以是广播的形式,也可以是点对点的。(后来参看了下JMS,其中有pub/sub的模式(即订阅模式),不过,对于异步消息的传递来说,这个可以不必实现)

消息服务

消息服务可以将一大堆分布在不同物理机上的应用整合起来,进行通信,可以将一些小的应用整合为一个大的,可用的应用系统

用一个例子来说吧:

  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(null0);  
  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机制),不过对于寻址方面还没有做进一步的处理,有时间再来完善吧。

消息服务的实现

下面我把消息服务的主要实现部分贴出来分析一下:

  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会立即返回,然后工作线程启动,取出消息并将其分发到合适的监听器上。

可能,对同步的处理上考虑不够周全,下来再继续修改。

抱歉!评论已关闭.