Spring+ActiveMQ+Flex- 智慧公交

智能公交调度系统-系统结合了GPSGIS GPRS 等,将车辆的状态信息实时传到调度中心,调度中心可以自动调度和监控车辆。通过将GPS接入后台在通过消息中间件将消息发送到前端,前端可以实时看到车辆运行状态、运行轨迹等信息。该县的公交数量有280辆,我们采用BlazeDS(免费)完全可以胜任,LCDS(商业)比较昂贵,但性能好。

那就简单介绍一下是以Flex为前台,结合BlazeDS和ActiveMQ以及Spring实现接收JMS消息的方法(publish/subscribe模式)。在消息订阅上采用UDP还是TCP根据具体情况具体选择,UDP传输速度快,TCP传输速度不如UDP,但可靠性好。视频传输、聊天软件大多采用的都是UDP。

具体的实现方式是:

1.用Spring中配置的Sender bean的send()方法向ActiveMQ发送JMS消息;

2.用Spring中配置的Receiver bean 的receive()方法从ActiveMQ接收消息;

3.然后通过BlazeDS的messaging模式将消息发送到Flex的消息订阅者上(推送到客户端)。

本例需要用到的环境包括:FlexPlugin、MyEclipse、ActiveMQ、BlazeDS

一.Blazeds

blazeDS采用amf协议。该协议可以传输Object,Array, Date, XML。由于AMF采用二进制编码,这种方式可以高度压缩数据,因此非常适合用来传递大量的资料。数据量越大,FlashRemoting的传输效能就越高,远远超过WebService。至于XML,LoadVars和loadVariables(),它们使用纯文本的传输方式,效能就更不能与FlashRemoting相提并论了。

将下载的blazeds.war 拷贝到tomcat webapp目录下,运行tomcat。Tomcat webapp目录下会生成blazeds文件夹。

二.ActiveMQ

ActiveMQ是Apache出品,最流行的、功能强大的即时通讯和集成模式的开源服务器。ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现。提供客户端支持跨语言和协议,带有易于在充分支持JMS 1.1和1.4使用J2EE企业集成模式和许多先进的功能。

到官网下载activeMQ5.9 修改activeMQ conf文件夹下activemq.xml配置文件,加入UDP传输方式(<transportConnector name="udp" uri="udp://0.0.0.0:8123" />

activemq.xml

  1. -<!--LicensedtotheApacheSoftwareFoundation(ASF)underoneormore
  2. contributorlicenseagreements.SeetheNOTICEfiledistributedwith
  3. thisworkforadditionalinformationregardingcopyrightownership.
  4. TheASFlicensesthisfiletoYouundertheApacheLicense,Version2.0
  5. (the"License");youmaynotusethisfileexceptincompliancewith
  6. theLicense.YoumayobtainacopyoftheLicenseat
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unlessrequiredbyapplicablelaworagreedtoinwriting,software
  9. distributedundertheLicenseisdistributedonan"ASIS"BASIS,
  10. WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
  11. SeetheLicenseforthespecificlanguagegoverningpermissionsand
  12. limitationsundertheLicense.
  13. -->
  14. -<!--STARTSNIPPET:example
  15. -->
  16. -<beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://activemq.apache.org/schema/corehttp://activemq.apache.org/schema/core/activemq-core.xsd">
  17. -<!--Allowsustousesystempropertiesasvariablesinthisconfigurationfile
  18. -->
  19. -<beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  20. -<propertyname="locations">
  21. <value>file:${activemq.conf}/credentials.properties</value>
  22. </property>
  23. </bean>
  24. -<!--Allowslogsearchinginhawtioconsole
  25. -->
  26. <beanid="logQuery"class="org.fusesource.insight.log.log4j.Log4jLogQuery"lazy-init="false"scope="singleton"init-method="start"destroy-method="stop"/>
  27. -<!--The<broker>elementisusedtoconfiguretheActiveMQbroker.
  28. -->
  29. -<brokerxmlns="http://activemq.apache.org/schema/core"brokerName="localhost"dataDirectory="${activemq.data}">
  30. -<destinationPolicy>
  31. -<policyMap>
  32. -<policyEntries>
  33. -<policyEntrytopic=">">
  34. -<!--TheconstantPendingMessageLimitStrategyisusedtoprevent
  35. slowtopicconsumerstoblockproducersandaffectotherconsumers
  36. bylimitingthenumberofmessagesthatareretained
  37. Formoreinformation,see:
  38. http://activemq.apache.org/slow-consumer-handling.html
  39. -->
  40. -<pendingMessageLimitStrategy>
  41. <constantPendingMessageLimitStrategylimit="1000"/>
  42. </pendingMessageLimitStrategy>
  43. </policyEntry>
  44. </policyEntries>
  45. </policyMap>
  46. </destinationPolicy>
  47. -<!--ThemanagementContextisusedtoconfigurehowActiveMQisexposedin
  48. JMX.Bydefault,ActiveMQusestheMBeanserverthatisstartedby
  49. theJVM.Formoreinformation,see:
  50. http://activemq.apache.org/jmx.html
  51. -->
  52. -<managementContext>
  53. <managementContextcreateConnector="false"/>
  54. </managementContext>
  55. -<!--Configuremessagepersistenceforthebroker.Thedefaultpersistence
  56. mechanismistheKahaDBstore(identifiedbythekahaDBtag).
  57. Formoreinformation,see:
  58. http://activemq.apache.org/persistence.html
  59. -->
  60. -<persistenceAdapter>
  61. <kahaDBdirectory="${activemq.data}/kahadb"/>
  62. </persistenceAdapter>
  63. -<!--ThesystemUsagecontrolsthemaximumamountofspacethebrokerwill
  64. usebeforedisablingcachingand/orslowingdownproducers.Formoreinformation,see:
  65. http://activemq.apache.org/producer-flow-control.html
  66. -->
  67. -<systemUsage>
  68. -<systemUsage>
  69. -<memoryUsage>
  70. <memoryUsagepercentOfJvmHeap="70"/>
  71. </memoryUsage>
  72. -<storeUsage>
  73. <storeUsagelimit="100gb"/>
  74. </storeUsage>
  75. -<tempUsage>
  76. <tempUsagelimit="50gb"/>
  77. </tempUsage>
  78. </systemUsage>
  79. </systemUsage>
  80. -<!--ThetransportconnectorsexposeActiveMQoveragivenprotocolto
  81. clientsandotherbrokers.Formoreinformation,see:
  82. http://activemq.apache.org/configuring-transports.html
  83. -->
  84. -<transportConnectors>
  85. -<!--DOSprotection,limitconcurrentconnectionsto1000andframesizeto100MB
  86. -->
  87. <transportConnectorname="openwire"uri="tcp://0.0.0.0:61616?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
  88. <transportConnectorname="udp"uri="udp://0.0.0.0:8123"/>
  89. <transportConnectorname="amqp"uri="amqp://0.0.0.0:5672?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
  90. <transportConnectorname="stomp"uri="stomp://0.0.0.0:61613?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
  91. <transportConnectorname="mqtt"uri="mqtt://0.0.0.0:1883?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
  92. <transportConnectorname="ws"uri="ws://0.0.0.0:61614?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
  93. </transportConnectors>
  94. -<!--destroythespringcontextonshutdowntostopjetty
  95. -->
  96. -<shutdownHooks>
  97. <beanxmlns="http://www.springframework.org/schema/beans"class="org.apache.activemq.hooks.SpringContextHook"/>
  98. </shutdownHooks>
  99. </broker>
  100. -<!--Enablewebconsoles,RESTandAjaxAPIsanddemos
  101. Thewebconsolesrequiresbydefaultlogin,youcandisablethisinthejetty.xmlfile
  102. Takealookat${ACTIVEMQ_HOME}/conf/jetty.xmlformoredetails
  103. -->
  104. <importresource="jetty.xml"/>
  105. </beans>
  106. -<!--ENDSNIPPET:example
  107. -->
  108. 

三.创建 web project(j2ee 5.0)

Spring+ActiveMQ+Flex- 智慧公交_第1张图片

将tomcat blazeds文件夹中的文件覆盖掉 工程SpringFlexMQWebRoot下的文件。

四.Web.xml配置

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. -<web-appversion="2.5"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  3. -<welcome-file-list>
  4. <welcome-file>index.jsp</welcome-file>
  5. </welcome-file-list>
  6. -<listener>
  7. <listener-class>flex.messaging.HttpFlexSession</listener-class>
  8. </listener>
  9. -<servlet>
  10. <servlet-name>flex</servlet-name>
  11. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  12. -<init-param>
  13. <param-name>contextConfigLocation</param-name>
  14. <param-value>classpath*:applicationContext.xml</param-value>
  15. </init-param>
  16. <load-on-startup>1</load-on-startup>
  17. </servlet>
  18. -<servlet-mapping>
  19. <servlet-name>flex</servlet-name>
  20. <url-pattern>/messagebroker/*</url-pattern>
  21. </servlet-mapping>
  22. -<servlet>
  23. <servlet-name>MessageBrokerServlet</servlet-name>
  24. <servlet-class>flex.messaging.MessageBrokerServlet</servlet-class>
  25. -<init-param>
  26. <param-name>services.configuration.file</param-name>
  27. <param-value>/WEB-INF/flex/services-config.xml</param-value>
  28. </init-param>
  29. <load-on-startup>1</load-on-startup>
  30. </servlet>
  31. -<servlet>
  32. <servlet-name>ControlServlet1</servlet-name>
  33. <servlet-class>com.test.jms.servlet.ControlServlet1</servlet-class>
  34. </servlet>
  35. -<servlet-mapping>
  36. <servlet-name>ControlServlet1</servlet-name>
  37. <url-pattern>/ControlServlet1</url-pattern>
  38. </servlet-mapping>
  39. </web-app>
  40. 

SSH整合的时候会注册spring 的ContextLoaderListene,但在这里给去掉了。似乎不是完美,这些问题以后会慢慢解决。

五.工程建好以后可以看到flex文件夹里的四个配置文件,修改配置文件。

1.messaging-config.xml

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. -<serviceid="message-service"class="flex.messaging.services.MessageService">
  3. -<adapters>
  4. <adapter-definitionid="actionscript"class="flex.messaging.services.messaging.adapters.ActionScriptAdapter"default="true"/>
  5. -<!--<adapter-definitionid="jms"class="flex.messaging.services.messaging.adapters.JMSAdapter"/>
  6. -->
  7. </adapters>
  8. -<default-channels>
  9. <channelref="my-polling-amf"/>
  10. <channelref="my-streaming-amf"/>
  11. </default-channels>
  12. </service>
  13. 
2.proxy-config.xml

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. -<serviceid="proxy-service"class="flex.messaging.services.HTTPProxyService">
  3. -<properties>
  4. -<connection-manager>
  5. <max-total-connections>100</max-total-connections>
  6. <default-max-connections-per-host>2</default-max-connections-per-host>
  7. </connection-manager>
  8. <allow-lax-ssl>true</allow-lax-ssl>
  9. </properties>
  10. -<adapters>
  11. <adapter-definitionid="http-proxy"class="flex.messaging.services.http.HTTPProxyAdapter"default="true"/>
  12. <adapter-definitionid="soap-proxy"class="flex.messaging.services.http.SOAPProxyAdapter"/>
  13. </adapters>
  14. -<default-channels>
  15. <channelref="my-amf"/>
  16. </default-channels>
  17. <destinationid="DefaultHTTP"/>
  18. </service>
  19. 
3.remoting-config.xml

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. -<serviceid="remoting-service"class="flex.messaging.services.RemotingService">
  3. -<adapters>
  4. <adapter-definitionid="java-object"class="flex.messaging.services.remoting.adapters.JavaAdapter"default="true"/>
  5. </adapters>
  6. -<default-channels>
  7. <channelref="my-amf"/>
  8. </default-channels>
  9. </service>
  10. 
4.services-config.xml

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. -<services-config>
  3. -<services>
  4. <service-includefile-path="remoting-config.xml"/>
  5. <service-includefile-path="proxy-config.xml"/>
  6. <service-includefile-path="messaging-config.xml"/>
  7. </services>
  8. -<services>
  9. -<default-channels>
  10. <channelref="my-amf"/>
  11. </default-channels>
  12. </services>
  13. -<security>
  14. <login-commandclass="flex.messaging.security.TomcatLoginCommand"server="Tomcat"/>
  15. -<!--Uncommentthecorrectappserver
  16. <login-commandclass="flex.messaging.security.TomcatLoginCommand"server="JBoss">
  17. <login-commandclass="flex.messaging.security.JRunLoginCommand"server="JRun"/>
  18. <login-commandclass="flex.messaging.security.WeblogicLoginCommand"server="Weblogic"/>
  19. <login-commandclass="flex.messaging.security.WebSphereLoginCommand"server="WebSphere"/>
  20. -->
  21. -<!--
  22. <security-constraintid="basic-read-access">
  23. <auth-method>Basic</auth-method>
  24. <roles>
  25. <role>guests</role>
  26. <role>accountants</role>
  27. <role>employees</role>
  28. <role>managers</role>
  29. </roles>
  30. </security-constraint>
  31. -->
  32. </security>
  33. -<channels>
  34. -<channel-definitionid="my-amf"class="mx.messaging.channels.AMFChannel">
  35. <endpointurl="http://{server.name}:{server.port}/{context.root}/messagebroker/amf"class="flex.messaging.endpoints.AMFEndpoint"/>
  36. </channel-definition>
  37. -<channel-definitionid="my-secure-amf"class="mx.messaging.channels.SecureAMFChannel">
  38. <endpointurl="https://{server.name}:{server.port}/{context.root}/messagebroker/amfsecure"class="flex.messaging.endpoints.SecureAMFEndpoint"/>
  39. -<properties>
  40. <add-no-cache-headers>false</add-no-cache-headers>
  41. </properties>
  42. </channel-definition>
  43. -<channel-definitionid="my-polling-amf"class="mx.messaging.channels.AMFChannel">
  44. <endpointurl="http://{server.name}:{server.port}/{context.root}/messagebroker/amfpolling"class="flex.messaging.endpoints.AMFEndpoint"/>
  45. -<properties>
  46. <polling-enabled>true</polling-enabled>
  47. <polling-interval-seconds>4</polling-interval-seconds>
  48. </properties>
  49. </channel-definition>
  50. -<channel-definitionid="my-streaming-amf"class="mx.messaging.channels.StreamingAMFChannel">
  51. <endpointurl="http://{server.name}:{server.port}/{context.root}/messagebroker/streamingamf"class="flex.messaging.endpoints.StreamingAMFEndpoint"/>
  52. -<properties>
  53. <idle-timeout-minutes>0</idle-timeout-minutes>
  54. <max-streaming-clients>100</max-streaming-clients>
  55. <server-to-client-heartbeat-millis>5000</server-to-client-heartbeat-millis>
  56. -<user-agent-settings>
  57. <user-agentmatch-on="MSIE"kickstart-bytes="2048"max-streaming-connections-per-session="100"/>
  58. <user-agentmatch-on="Firefox"kickstart-bytes="2048"max-streaming-connections-per-session="100"/>
  59. </user-agent-settings>
  60. </properties>
  61. </channel-definition>
  62. </channels>
  63. -<logging>
  64. -<targetclass="flex.messaging.log.ConsoleTarget"level="Error">
  65. -<properties>
  66. <prefix>[BlazeDS]</prefix>
  67. <includeDate>false</includeDate>
  68. <includeTime>false</includeTime>
  69. <includeLevel>false</includeLevel>
  70. <includeCategory>false</includeCategory>
  71. </properties>
  72. -<filters>
  73. <pattern>Endpoint.*</pattern>
  74. <pattern>Service.*</pattern>
  75. <pattern>Configuration</pattern>
  76. </filters>
  77. </target>
  78. </logging>
  79. -<system>
  80. -<redeploy>
  81. <enabled>false</enabled>
  82. </redeploy>
  83. </system>
  84. </services-config>
  85. 

六.Spring的配置文件applicationContext.xml

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. -<beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"xmlns:flex="http://www.springframework.org/schema/flex"xmlns:amq="http://activemq.apache.org/schema/core"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/flexhttp://www.springframework.org/schema/flex/spring-flex-1.0.xsdhttp://activemq.apache.org/schema/corehttp://activemq.apache.org/schema/core/activemq-core-5.2.0.xsd">
  3. -<!--配置messagebroker
  4. -->
  5. -<flex:message-brokerid="_messageBroker">
  6. <flex:message-servicedefault-channels="my-streaming-amf,my-polling-amf"/>
  7. </flex:message-broker>
  8. -<!--配置消息信道,相当于之前messaging-config.xml文件中信道配置
  9. -->
  10. <flex:message-destinationid="market-data-feed"channels="my-streaming-amf,my-polling-amf"allow-subtopics="true"subtopic-separator="."/>
  11. <beanclass="org.springframework.flex.servlet.MessageBrokerHandlerAdapter"/>
  12. <beanid="Reciver"class="com.test.jms.util.Receive"/>
  13. <beanid="Sender"class="com.test.jms.util.Sender"/>
  14. <flex:remoting-destinationref="Reciver"/>
  15. <flex:remoting-destinationref="Sender"/>
  16. </beans>
  17. 

七.Java后台代码

1.Sender.java

  1. packagecom.test.jms.util;
  2. importjavax.jms.Connection;
  3. importjavax.jms.ConnectionFactory;
  4. importjavax.jms.Destination;
  5. importjavax.jms.JMSException;
  6. importjavax.jms.MessageProducer;
  7. importjavax.jms.Session;
  8. importorg.apache.activemq.ActiveMQConnection;
  9. importorg.apache.activemq.ActiveMQConnectionFactory;
  10. publicclassSender{
  11. publicvoidsend(Strings){
  12. try{
  13. //连接工厂,负责创建Connection
  14. ConnectionFactoryconnectionFactory=null;
  15. //负责创建Session
  16. Connectionconnection=null;
  17. //创建MessageProducer(用来发消息)和MessageConsumer(用来接收消息)
  18. Sessionsession=null;
  19. //消息的目的地
  20. Destinationdestination=null;
  21. connectionFactory=newActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,"udp://192.168.1.22:8123");
  22. connection=connectionFactory.createConnection();
  23. connection.start();
  24. session=connection.createSession(Boolean.FALSE,Session.AUTO_ACKNOWLEDGE);
  25. //创建Topic,名字为myTopic
  26. destination=session.createTopic("myTopic");
  27. MessageProducermessage_producer=session.createProducer(destination);
  28. //通过消息生产者发出消息
  29. message_producer.send(session.createTextMessage(s));
  30. }catch(JMSExceptione){
  31. e.printStackTrace();
  32. }
  33. }
  34. }

2.Receive.java

  1. packagecom.test.jms.util;
  2. importjavax.jms.Connection;
  3. importjavax.jms.ConnectionFactory;
  4. importjavax.jms.Destination;
  5. importjavax.jms.JMSException;
  6. importjavax.jms.Message;
  7. importjavax.jms.MessageConsumer;
  8. importjavax.jms.MessageListener;
  9. importjavax.jms.TextMessage;
  10. importjavax.jms.Session;
  11. importflex.messaging.MessageBroker;
  12. importflex.messaging.messages.AsyncMessage;
  13. importflex.messaging.messages.AcknowledgeMessage;
  14. importflex.messaging.messages.CommandMessage;
  15. importflex.messaging.util.UUIDUtils;
  16. importorg.apache.activemq.ActiveMQConnection;
  17. importorg.apache.activemq.ActiveMQConnectionFactory;
  18. importflex.messaging.endpoints.Endpoint;
  19. publicclassReceive{
  20. privatestaticConnectionFactoryconnectionFactory=null;
  21. privatestaticConnectionconnection=null;
  22. privatestaticSessionsession=null;
  23. privatestaticDestinationdestination=null;
  24. privatestaticMessageConsumermessageConsumer=null;
  25. publicvoiddoReceive(){
  26. try{
  27. connectionFactory=newActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,"udp://192.168.1.22:8123");
  28. connection=connectionFactory.createConnection();
  29. connection.start();
  30. session=connection.createSession(Boolean.FALSE,Session.AUTO_ACKNOWLEDGE);
  31. destination=session.createTopic("myTopic");
  32. if(messageConsumer==null){
  33. messageConsumer=session.createConsumer(destination);
  34. //重写MessageListener类的onMessage方法
  35. messageConsumer.setMessageListener(newMessageListener(){
  36. publicvoidonMessage(Messagemessage){
  37. try{
  38. TextMessagetextMessage=(TextMessage)message;
  39. Stringmsg=null;
  40. msg=textMessage.getText();
  41. System.out.println(msg);
  42. //获取消息代理,此处的参数就是Spring配置文件中配置的messagebroker的id
  43. MessageBrokermessageBroker=MessageBroker.getMessageBroker("_messageBroker");
  44. StringclientID=UUIDUtils.createUUID();
  45. //创建AsyncMessage类的对象是为了Flex端用Messaging模式接收消息
  46. AsyncMessageasynMsg=newAsyncMessage();
  47. //设置消息的地址,这个必须跟Spring配置文件中信道的destination一致
  48. asynMsg.setDestination("market-data-feed");
  49. //flex可以通过header过滤消息
  50. asynMsg.setHeader("msg","new");
  51. asynMsg.setClientId(clientID);
  52. asynMsg.setMessageId(UUIDUtils.createUUID());
  53. asynMsg.setTimestamp(System.currentTimeMillis());
  54. asynMsg.setBody(msg);
  55. messageBroker.routeMessageToService(asynMsg,null);
  56. }catch(JMSExceptione){
  57. e.printStackTrace();
  58. try{
  59. connection.close();
  60. }catch(JMSExceptione1){
  61. e1.printStackTrace();
  62. }
  63. }
  64. }
  65. });
  66. }
  67. }catch(Exceptione){
  68. }
  69. }
  70. }

3.ControlServlet1.java

  1. packagecom.test.jms.servlet;
  2. importjava.io.IOException;
  3. importjava.io.PrintWriter;
  4. importjavax.servlet.ServletContext;
  5. importjavax.servlet.ServletException;
  6. importjavax.servlet.http.HttpServlet;
  7. importjavax.servlet.http.HttpServletRequest;
  8. importjavax.servlet.http.HttpServletResponse;
  9. importorg.springframework.context.ApplicationContext;
  10. importorg.springframework.web.context.WebApplicationContext;
  11. importorg.springframework.web.context.support.WebApplicationContextUtils;
  12. publicclassControlServlet1extendsHttpServlet{
  13. publicvoidinit()throwsServletException{
  14. }
  15. publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
  16. throwsServletException,IOException{
  17. doPost(request,response);
  18. }
  19. publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
  20. throwsServletException,IOException{
  21. }
  22. }

八.前台Flex的代码

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <s:Applicationxmlns:fx="http://ns.adobe.com/mxml/2009"
  3. xmlns:s="library://ns.adobe.com/flex/spark"
  4. xmlns:mx="library://ns.adobe.com/flex/mx"
  5. minWidth="955"minHeight="600"creationComplete="init();">
  6. <fx:Script>
  7. <![CDATA[
  8. importmx.controls.Alert;
  9. importmx.messaging.events.MessageEvent;
  10. importmx.messaging.events.MessageFaultEvent;
  11. importmx.rpc.events.FaultEvent;
  12. importmx.messaging.ChannelSet;
  13. importmx.messaging.channels.AMFChannel;
  14. importmx.messaging.channels.SecureStreamingAMFChannel;
  15. importmx.messaging.channels.StreamingAMFChannel;
  16. protectedfunctioninit():void{
  17. //调用后台的Receive类中的doReceive方法,实现订阅和监听消息
  18. ReceiveMessage.doReceive();
  19. //给我们定义的consumer对象指定一个信道,我们定义了两种信道,在services-config.xml文件中,此处选用my-streaming-amf
  20. consumer.subscribe();
  21. }
  22. //按钮点击触发的操作
  23. protectedfunctionbtnSendMessage_clickHandler(event:MouseEvent):void
  24. {
  25. Send.send(myinput.text);
  26. myinput.text="";
  27. }
  28. //点击按钮后操作失败的处理
  29. protectedfunctionSend_faultHandler(event:FaultEvent):void
  30. {
  31. Alert.show("sendisfail,because:"+event.fault.toString());
  32. }
  33. //收到消息的失败处理
  34. protectedfunctionReceiveMessage_faultHandler(event:FaultEvent):void
  35. {
  36. Alert.show("receiveisfail,because:"+event.fault.toString());
  37. }
  38. //生产者收到消息的错误处理
  39. protectedfunctionconsumer_faultHandler(event:MessageFaultEvent):void
  40. {
  41. Alert.show("error");
  42. Alert.show(event.faultString);
  43. }
  44. //生产者收到消息后的处理
  45. protectedfunctionconsumer_messageHandler(event:MessageEvent):void
  46. {
  47. txtMessage.text=txtMessage.text+event.message.body.toString()+"\n";
  48. }
  49. ]]>
  50. </fx:Script>
  51. <fx:Declarations>
  52. <!--将非可视元素(例如服务、值对象)放在此处-->
  53. <!--此处定义一个consumer,需要使用它来订阅消息,订阅了以后才能接收到后台发来的数据。这里的关键是要定义destination,destination的值和后台messaging-config.xml定义的destination的值相同-->
  54. <s:ConsumerchannelSet="{cs}"id="consumer"destination="market-data-feed"fault="consumer_faultHandler(event)"message="consumer_messageHandler(event)"/>
  55. <!--此处定义个接收消息的类,与后台的接收消息的POJO对应,通过它来定义consumer和调用监听方法-->
  56. <s:RemoteObjectid="ReceiveMessage"channelSet="{amf_channel}"destination="Reciver"
  57. fault="ReceiveMessage_faultHandler(event)"/>
  58. <!--此处定义个发送消息的类,与后台的发送消息的POJO对应,通过它向ActiveMQ发送消息-->
  59. <s:RemoteObjectid="Send"channelSet="{amf_channel}"destination="Sender"
  60. fault="Send_faultHandler(event)"/>
  61. <s:AMFChannelid="myamfChannel"
  62. url="http://192.168.1.22:8088/SpringFlexMQ/messagebroker/amf"/>
  63. <mx:ChannelSetid="amf_channel"channels="{[myamfChannel]}"/>
  64. <s:ChannelSetid="cs">
  65. <s:StreamingAMFChannelurl="http://192.168.1.22:8088/SpringFlexMQ/messagebroker/streamingamf"/>
  66. </s:ChannelSet>
  67. </fx:Declarations>
  68. <mx:VBoxheight="100%"horizontalAlign="center"width="100%"verticalAlign="middle"chromeColor="#9F9F9F"dropShadowVisible="true"backgroundColor="#6A232F"backgroundAlpha="0.6">
  69. <mx:VBoxwidth="438"verticalAlign="middle"horizontalAlign="center"paddingBottom="5"paddingTop="5"paddingLeft="5"paddingRight="5"backgroundColor="#87194D"focusColor="#6C1D2A"cornerRadius="10">
  70. <s:VGrouphorizontalAlign="center"gap="11"paddingBottom="5"paddingTop="5"paddingLeft="5"paddingRight="5"contentBackgroundColor="#EDEDED">
  71. <mx:TextAreaid="txtMessage"x="62"y="100"width="408"height="249"dropShadowVisible="true"text=""borderColor="#97515D"chromeColor="#F0BABA"contentBackgroundColor="#F2FCFA"/>
  72. <s:TextInputid="myinput"x="0"y="250"width="408"height="42"contentBackgroundColor="#F4F9F8"borderColor="#8B3B3B"/>
  73. <mx:Buttonid="btnSendMessage"x="0"y="302"label="Send"click="btnSendMessage_clickHandler(event)"chromeColor="#97D2EB"paddingBottom="0"/>
  74. </s:VGroup>
  75. </mx:VBox>
  76. </mx:VBox>
  77. </s:Application>

九.启动ActiveMQ

Spring+ActiveMQ+Flex- 智慧公交_第2张图片

十.启动程序

Spring+ActiveMQ+Flex- 智慧公交_第3张图片

十一.总结

1.ActiveMQ如何将对象推送到前端,前端又是如何接受对象?

2.Spring如何更有效地管理ActiveMQ?

3. 如何实现订阅的信息筛选?

4. jar包下载地址http://download.csdn.net/detail/allen_gang/6659767



你可能感兴趣的:(activemq)