7、使用ActiveMQ创建java应用程序

完整配置的代理可以为来自相同应用程序(使用VM协议)的客户机和来自远程应用程序的客户机提供服务。

7、使用ActiveMQ创建java应用程序 - 图1

使用java嵌入ActiveMQ

起点:org.apache.activemq.broker.BrokerService

BrokerFactory:使用ActiveMQ URI创建代理的实例

xbean URI告诉代理在classpath类路径下搜索给定的XML配置文件

使用spring嵌入ActiveMQ

使用一个纯净的Spring XML语法和ActiveMQ,,在spring配置文件中定义BrokerService作为一个bean

默认情况下,ActiveMQ使用spring和Apache XBean进行内部配置。XBean提供定义和使用自定义的XML语法的能力

  1. org.apache.xbean.spring.context.FileSystemXmlApplicationContext context = new
  2. FileSystemXmlApplicationContext(config);

实现JMS的请求/应答

请求/应答场景涉及发送消息(request)并期望接收消息(reply)的应用程序。世界上一些最可扩展性系统是使用异步处理的。

在下面的图表中,生产者以JMS消息的形式创建一个请求,并设置两个请求重要的属性:

相关联ID和应答目的地。客户端在应答目的地配置一个消费者进行监听。

其次,工作人员接收请求,处理请求,并使用请求消息的JMSReplyTo属性向指定的目的地发送应答消息。

7、使用ActiveMQ创建java应用程序 - 图2

增加程序可伸缩性,只需要增加worker来处理负载。

分配相关ID:

  1. response.setJMSCorrelationID(message.getJMSCorrelationID());

在客户端,发送请求

  1. TextMessage txtMessage = session.createTextMessage();
  2. txtMessage.setText(request);
  3. txtMessage.setJMSReplyTo(tempDest);
  4. txtMessage.setJMSCorrelationID(correlationId);
  5. this.producer.send(txtMessage);

等待应答

  1. tempDest = session.createTemporaryQueue();
  2. consumer = session.createConsumer(tempDest);
  3. consumer.setMessageListener(this);
  4. public void onMessage(Message message) {
  5. }

使用Spring编写JMS客户机

配置JMS连接配置

  1. <bean id="jmsConnectionFactory"
  2. class="org.apache.activemq.ActiveMQConnectionFactory">
  3. <property name="brokerURL" value="tcp://localhost:61616" />
  4. <property name="userName" value="admin" />
  5. <property name="password" value="password" />
  6. </bean>

配置JMS目的地配置

  1. <bean id="cscoDest" class="org.apache.activemq.command.ActiveMQTopic">
  2. <constructor-arg value="STOCKS.CSCO" />
  3. </bean>

创建JMS消费者

  1. <bean id="cscoConsumer"
  2. class="org.springframework.jms.listener.DefaultMessageListenerContainer">
  3. <property name="connectionFactory" ref="jmsConnectionFactory" />
  4. <property name="destination" ref="cscoDest" />
  5. <property name="messageListener" ref="portfolioListener" />
  6. </bean>

创建JMS生产者

JmsTemplate是一个发送消息的方便类

  1. <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
  2. <property name="connectionFactory" ref="pooledJmsConnectionFactory" />
  3. </bean>
  4. <bean id="stockPublisher" class="org….book.ch7.spring.SpringPublisher">
  5. <property name="template" ref="jmsTemplate" />
  6. <property name="destinations">
  7. <list>
  8. <ref local="cscoDest" />
  9. <ref local="orclDest" />
  10. </list>
  11. </property>
  12. </bean>
  13. Destination destination = destinations[idx];
  14. template.send(destination, getStockMessageCreator(destination));