<dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-all</artifactId> <version>5.4.3</version> </dependency> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-web</artifactId> <version>5.4.3</version> <exclusions> <exclusion> <artifactId>tools</artifactId> <groupId>com.sun</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-pool</artifactId> <version>5.4.3</version> </dependency>
@Service @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class MqTaskReceiver implements MessageListener { @Override public void onMessage(Message message) { try { if (message == null) { return; } String msg = ((TextMessage) message).getText(); int m = Integer.valueOf(msg); msg += (m % 10 == 0 ? "\n" : "\t"); System.out.print(msg); Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } } }
package com.chj.common.util; public class ActiveMqUtils { private static final int MESSAGE_TIME_TO_LIVE = 1 * 3600 * 1000; private String brokerURL; public String getBrokerURL() { return brokerURL; } public void setBrokerURL(String brokerURL) { this.brokerURL = brokerURL; try { init(); } catch (JMSException e) { e.printStackTrace(); } } private ConnectionFactory connectionFactory; private Connection connection; private Session session; private boolean isInit = false; private Map<String, MessageProducer> messageProducers = new HashMap<String, MessageProducer>(); private static Map<MessageConsumer, Session> mcs = new HashMap<MessageConsumer, Session>(); public void init() throws JMSException { if (!isInit) { isInit = true; connectionFactory = new ActiveMQConnectionFactory(brokerURL); connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } } public MessageProducer getMessageProducer(String queueName) throws JMSException { MessageProducer producer = messageProducers.get(queueName); if (producer != null) return producer; producer = session.createProducer(session.createQueue(queueName)); producer.setTimeToLive(MESSAGE_TIME_TO_LIVE); producer.setDeliveryMode(1); messageProducers.put(queueName, producer); return producer; } public MessageProducer getTopicMessageProducer(String topicName) throws JMSException { MessageProducer producer = messageProducers.get(topicName); if (producer != null) return producer; producer = session.createProducer(session.createTopic(topicName)); producer.setTimeToLive(MESSAGE_TIME_TO_LIVE); producer.setDeliveryMode(1); messageProducers.put(topicName, producer); return producer; } public void registTopicListener(String topicName, MessageListener messageListener) throws JMSException { MessageConsumer messageConsumer = createTopicMessageConsumer(topicName); messageConsumer.setMessageListener(messageListener); } public void registQueueListener(String queueName, MessageListener messageListener) throws JMSException { MessageConsumer messageConsumer = createMessageConsumer(queueName); messageConsumer.setMessageListener(messageListener); } public MessageConsumer createMessageConsumer(String queueName) throws JMSException { Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer mc = s.createConsumer(session.createQueue(queueName)); mcs.put(mc, s); return mc; } public MessageConsumer createTopicMessageConsumer(String topicName) throws JMSException { Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer mc = s.createConsumer(session.createTopic(topicName)); mcs.put(mc, s); return mc; } public void sendQueueMessage(String queueName, Message message) throws JMSException { getMessageProducer(queueName).send(message); } public static void closeSession(MessageConsumer mc) { try { mcs.get(mc).close(); } catch (JMSException e) { e.printStackTrace(); } } public Session getSession() { return session; } public static Map<String, Object> simpleBeanToMap(Object obj) throws IllegalArgumentException, IllegalAccessException { Map<String, Object> item = new HashMap<String, Object>(); Field[] fields = obj.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { boolean ss = fields[i].isAccessible(); fields[i].setAccessible(true); item.put(fields[i].getName(), fields[i].get(obj)); fields[i].setAccessible(ss); } return item; } public static <T> T simpleMapToBean(Map<String, Object> map, Class<T> clazz) throws InstantiationException, IllegalAccessException { Set<String> keyset = map.keySet(); T t = clazz.newInstance(); for (Iterator<String> iterator = keyset.iterator(); iterator.hasNext();) { String string = iterator.next(); try { Field field = clazz.getDeclaredField(string); if (field != null) { boolean f = field.isAccessible(); field.setAccessible(true); field.set(t, map.get(string)); field.setAccessible(f); } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } } return t; } public MapMessage createMapMessage() throws JMSException { return session.createMapMessage(); } public Message createMessage() throws JMSException { return session.createMessage(); } public void sendMessage(String queueName, String message) throws JMSException { MessageProducer producer = getMessageProducer(queueName); Session session = getSession(); TextMessage textMessage = session.createTextMessage(message); producer.send(textMessage); } }
<bean id="activeMqUtils" class="com.chj.common.util.ActiveMqUtils"> <property name="brokerURL"> <value>${activeMQ}</value> </property> </bean>
4. web.xml中配置
<listener> <listener-class>com.chj.web.listener.SystemContextListener</listener-class> </listener>
package com.chj.web.listener;public class SystemContextListener extends ContextLoaderListener { @Override public void contextInitialized(ServletContextEvent sce) { super.contextInitialized(sce); SpringUtils.setApplicationContext((WebApplicationContext) sce.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)); initActiveMQ(); } @Override public void contextDestroyed(ServletContextEvent event) { } private void initActiveMQ() { try { ActiveMqUtils mqUtils = (ActiveMqUtils) SpringUtils.getBean("activeMqUtils"); String queueName = "test"; MqTaskReceiver messageListener = (MqTaskReceiver) SpringUtils.getBean("mqTaskReceiver"); mqUtils.registQueueListener(queueName, messageListener); } catch (Exception e) { e.printStackTrace(); } } }
测试:
public class MqTest { public static void main(String[] args) { String[] locations = { "spring-web-config.xml" }; ApplicationContext ctx = new ClassPathXmlApplicationContext(locations); ActiveMqUtils mqUtils = (ActiveMqUtils) ctx.getBean("activeMqUtils"); String queueName = "test"; long begin = System.currentTimeMillis(); for (int i = 1; i <= 10; i++) { String message = i + ""; try { mqUtils.sendMessage(queueName, message,i-1); } catch (JMSException e) { e.printStackTrace(); } } long end = System.currentTimeMillis(); System.out.println(end - begin); } }