flex订阅JMS消息

来源:互联网 发布:金融类软件测试薪资 编辑:程序博客网 时间:2024/04/29 17:53

     adobe官方的BlazeDS使得flex访问外部数据的能力进一步加强。利用BlazeDS和JMS的消息机制可以实现数据的推送,从而实现页面的实时刷新。下边是我写的一个例子主要代码:

    环境为Flex Builder3 , BlazeDS , Tomcat5.5 , JDK5 , jms用apache的ActiveMQ5.1

    需要将activemq-all-5.1.0.jar放到classpath中

     服务端代码及配置:

    Jms发送数据,Sender.java

    public class Sender implements Runnable {
 
private Context envCtx = null;
 
 private ActiveMQConnectionFactory connectionFactory ;
 
 private TopicConnection connection ;
 
 private TopicSession session ;
 
 private ActiveMQTopic destination ;
 
 private TopicPublisher publisher;
 
 private Random random = new Random();
 
 private int i = 0 ;
 
 private void initializer(){
  Context initCtx;
  try {
   initCtx = new InitialContext();
   envCtx = (Context)initCtx.lookup("java:comp/env/jms");
   connectionFactory = (ActiveMQConnectionFactory)envCtx.lookup("ConnectionFactory");
   destination = (ActiveMQTopic)envCtx.lookup("topic/MyTopic");
   connection = connectionFactory.createTopicConnection();
   session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
   publisher = session.createPublisher(destination);
   connection.start();
  } catch (NamingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (JMSException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
 }
 
 private void send(){
  try {
   TextMessage message = session.createTextMessage();   
   String value = String.valueOf(random.nextInt(100));
   message.setText(value);
   publisher.publish(message);
   System.out.println("send " + value + " ok.");
  } catch (JMSException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
 }
 
 private void sendObj(){
  try {
   SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");  
   String time = simpleDateFormat.format(new Date());
   String index = String.valueOf(i++);
   String x = String.valueOf(random.nextInt(100));
   SampleBean bean = new SampleBean();
   bean.setId(index);
   bean.setName(time);
   bean.setValue(x);
   ObjectMessage objectMessage = session.createObjectMessage();
   objectMessage.setObject(bean);
   publisher.send(objectMessage);
    
   System.out.println("send obj x="+x+"-------------"+time);
  } catch (JMSException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 /* (non-Javadoc)
  * @see java.lang.Runnable#run()
  */
 public void run() {  
  try {
   initializer();
   connection.start();   
   while(true){
    sendObj();
    //int qq = random.nextInt(10);
    Thread.sleep(1000);    
   }
  } catch (JMSException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch(Exception e){
   e.printStackTrace();
  }
  
 }

}

 

该类是一个线程,启动后每一秒中发送一个对象JavaBean。

JMS的jndi配置:

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true">
    <Resource
        name="jms/ConnectionFactory"
        auth="Container"
        type="org.apache.activemq.ActiveMQConnectionFactory"
        description="JMS Connection Factory"
        factory="org.apache.activemq.jndi.JNDIReferenceFactory"
        brokerURL="tcp://192.168.19.2:61616"
        brokerName="LocalActiveMQBroker"
        useEmbeddedBroker="false"/>

    <Resource name="jms/topic/MyTopic"
        auth="Container"
        type="org.apache.activemq.command.ActiveMQTopic"
        factory="org.apache.activemq.jndi.JNDIReferenceFactory"
        physicalName="MY.TEST.FOO"/>
</Context>

context.xml , 放在WEB-INF/META-INF/下

BlazeDS配置文件:

services-config.xml中修改如下部分:

<channel-definition id="my-amf" class="mx.messaging.channels.AMFChannel">
           <endpoint url="http://192.168.5.27:8080/jmsTopic/messagebroker/amf" class="flex.messaging.endpoints.AMFEndpoint"/>
           <properties>
                <polling-enabled>true</polling-enabled>
                <polling-interval-millis>1000</polling-interval-millis>
            </properties>
        </channel-definition>

其中的url中的http://192.168.5.27:8080/jmsTopic为你实际的web工程的url

messaging-config.xml中添加:

 <destination id="message-destination">
  <properties>
   <jms>
    <destination-type>Topic</destination-type>
    <message-type>javax.jms.ObjectMessage</message-type>
    <connection-factory>java:comp/env/jms/ConnectionFactory</connection-factory>
    <destination-jndi-name>java:comp/env/jms/topic/MyTopic</destination-jndi-name>
    <delivery-mode>NON_PERSISTENT</delivery-mode>
    <message-priority>DEFAULT_PRIORITY</message-priority>
    <acknowledge-mode>AUTO_ACKNOWLEDGE</acknowledge-mode>
    <initial-context-environment>
     <property>
      <name>Context.INITIAL_CONTEXT_FACTORY</name>
      <value>org.apache.activemq.jndi.ActiveMQInitialContextFactory</value>
     </property>
     <property>
      <name>Context.PROVIDER_URL</name>
      <value>tcp://192.168.19.2:61616</value>
     </property>
    </initial-context-environment>
   </jms>
  </properties>
  <channels>
   <channel ref="my-amf"/>
  </channels>
  <adapter ref="jms"/>
 </destination>

Context.PROVIDER_URL为ActiveMQ的默认服务地址和端口

 

flex端的代码:

    <?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx='http://www.adobe.com/2006/mxml' backgroundGradientColors="[0xcfe4ff, 0xffffff]" paddingTop="5" paddingLeft="5" paddingRight="5" paddingBottom="0" applicationComplete="logon()">
 
 <mx:Script><![CDATA[
  import mx.collections.ArrayCollection;       
  import mx.rpc.events.FaultEvent;       
  import mx.messaging.*;       
  import mx.messaging.messages.*;       
  import mx.messaging.events.*;        
  import mx.controls.Alert;       
  [Bindable]
  private var dataArr:ArrayCollection = new ArrayCollection();
  
  private function messageHandler(event:MessageEvent):void { 
     trace(ValueVO(event.message.body).value + "-----" + new Date().toTimeString());
    
     var valueVo:ValueVO = ValueVO(event.message.body);
     var arr:Array = dataArr.source;
     arr.push(valueVo);
     dataArr.source = arr;
  }       
  private function acknowledgeHandler(event:MessageAckEvent):void{   
   
  }       
  private function faultHandler(event:MessageFaultEvent):void {         
   Alert.show(event.faultString);      
  }       
  private function logon():void {           
   consumer.subscribe(); 
  }       
 
 ]]> </mx:Script>
 <mx:Producer id="producer" destination="message-destination" acknowledge="acknowledgeHandler(event);" fault="faultHandler(event)"/>
 <mx:Consumer id="consumer" destination="message-destination" message="messageHandler(event)" acknowledge="acknowledgeHandler(event);" fault=" faultHandler(event)"/>
 <mx:Panel title="LineChart Controls Example"
        height="100%" width="100%" layout="horizontal">

        <mx:LineChart id="linechart" height="100%" width="100%"
            paddingLeft="5" paddingRight="5"
            showDataTips="true" dataProvider="{dataArr}">
               
            <mx:horizontalAxis>
                <mx:CategoryAxis categoryField="name"/>
            </mx:horizontalAxis>

            <mx:series>
                <mx:LineSeries yField="value"/>
            </mx:series>
        </mx:LineChart>    

    </mx:Panel>

</mx:Application>

其中的ValueVO对象是与JavaBean对应的vo , 里边只有id , name , value三个属性,均为String类型的。

该例子的功能是实现Jms给flex发送数据,flex展现实时线图。

 

以上是该例子的核心代码,如果有不清楚的地方,可以直接回复;或者联系我,我的邮箱是xieyf_0413@163.com

原创粉丝点击