- 配置connectionFactory
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"> <property name="brokerURL" value="tcp://localhost:61616"/> <property name="maxThreadPoolSize" value="50"/> </bean> <bean id="cachingConnectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory"> <property name="targetConnectionFactory" ref="connectionFactory" /> <property name="sessionCacheSize" value="5" /> </bean> <bean id="singleConnectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory"> <property name="targetConnectionFactory"> <ref local="connectionFactory"/> </property> </bean>
- 配置生产者
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"> <property name="connectionFactory" ref="cachingConnectionFactory"/> <property name="explicitQosEnabled" value="true"/> <property name="deliveryMode" value="2"/> </bean>
<bean id="destination" class="org.apache.activemq.command.ActiveMQTopic"> <constructor-arg value="20000" /> </bean> <!-- <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue"> <constructor-arg> <value>queue</value> </constructor-arg> </bean> -->public void messageSend(){
jmsTemplate.send(destination, new MessageCreator() { public Message createMessage(Session session) throws JMSException { return session.createTextMessage(message); } });
} - 配置消费者
//实现MessageListener接口 public class TopicMessageListener implements MessageListener { @Override public void onMessage(Message message) { try { String msgText = ((TextMessage) message).getText(); System.out.println("接收到的消息为:" + msgText); } catch (JMSException e) { e.printStackTrace(); } } }
<bean id="messageListener" class="com.TopicMessageListener" />
public void consumerStart(){ logger.info("启动消费者:" + connectionFactory + " [" + destination + "]"); DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer();//监听容器 listenerContainer.setConnectionFactory(connectionFactory);// listenerContainer.setDestination(destination);// listenerContainer.setMessageListener(messageListener);// //listenerContainer.setMessageSelector(messageSelector); //listenerContainer.setPubSubDomain(true); //listenerContainer.setPubSubNoLocal(false); //listenerContainer.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); //listenerContainer.setTaskExecutor(taskExecutor); listenerContainer.initialize(); listenerContainer.start();
}<!-- <bean id="container" class="org.springframework.jms.listener.DefaultMessageListenerContainer"> <property name="connectionFactory" ref="connectionFactory" /> <property name="destination" ref="destination" /> <property name="messageListener" ref="messageListener" /> </bean> -->
1.dos命令行切换到apache-activemq/bin目录下,执行命令activemq start
2.启动消费者(如果监听容器使用xml配置,则自动启动)
运行consumerStart方法
3.启动生产者
运行messageSend方法