activemq: jms api实现queue和topic生产者、消费者demo及spring api 实现queue生产者、消费者
一、jms api实现queue和topic生产者、消费者demo
1、queue
1.1、生产者
package com.hcb.mq.jmsapi.queue;
import java.util.Date;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
public class QueueProducer {
public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"tcp://localhost:61616");
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(Boolean.TRUE,
Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("jms-api-queue");
MessageProducer producer = session.createProducer(destination);
for (int i = 0; i < 3; i++) {
MapMessage message = session.createMapMessage();
message.setLong("count", new Date().getTime());
Thread.sleep(1000);
producer.send(message);
}
session.commit();
session.close();
connection.close();
}
}
1.2、消费者
package com.hcb.mq.jmsapi.queue;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
public class QueueCustomer {
private static Logger LOG = LoggerFactory.getLogger(QueueCustomer.class);
public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"tcp://localhost:61616");
Connection connection = connectionFactory.createConnection();
connection.start();
final Session session = connection.createSession(Boolean.TRUE,
Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("jms-api-queue");
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message msg) {
MapMessage message = (MapMessage) msg;
try {
LOG.info("收到消息:" + new Date(message.getLong("count")));
session.commit();
} catch (JMSException e) {
e.printStackTrace();
}
}
});
Thread.sleep(60 * 1000);
session.close();
connection.close();
}
}
2、topic
2.1、生产者
package com.hcb.mq.jmsapi.topic;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TopicMsgProducer {
private static Logger LOG = LoggerFactory.getLogger(TopicMsgProducer.class);
public void send() {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
"tcp://localhost:61616");
Connection conn = null;
try {
conn = factory.createConnection();
conn.start();
Session session = conn.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("jms-topic");
MessageProducer producer = session.createProducer(topic);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
producer.setTimeToLive(Message.DEFAULT_TIME_TO_LIVE);
for (int i = 0; i < 5; i++) {
TextMessage tmsg = session.createTextMessage();
tmsg.setText("早上你好 " + i);
producer.send(tmsg);
LOG.info("发送的消息:" + tmsg.getText());
}
session.close();
conn.close();
} catch (JMSException e) {
e.printStackTrace();
} finally {
}
}
public static void main(String[] args) throws Exception {
new TopicMsgProducer().send();
}
}
2.2、订阅者
package com.hcb.mq.jmsapi.topic;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicSubscriber;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TopicMsgSubscriber {
private static Logger LOG = LoggerFactory
.getLogger(TopicMsgSubscriber.class);
private String name;
TopicMsgSubscriber(String name) {
this.name = name;
}
public void receive() throws InterruptedException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
"tcp://localhost:61616");
Connection conn = null;
try {
conn = factory.createConnection();
conn.setClientID(this.name);
conn.start();
final Session session = conn.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("jms-topic");
TopicSubscriber subsriber = session.createDurableSubscriber(topic,
this.name);
subsriber.setMessageListener(new MessageListener() {
public void onMessage(Message msg) {
TextMessage message = (TextMessage) msg;
try {
LOG.info(name + " received message: "
+ message.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
Thread.sleep(60 * 1000);
session.close();
conn.close();
LOG.info(this.name + " receive over");
} catch (JMSException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws Exception {
new Thread() {
public void run() {
try {
new TopicMsgSubscriber("subscriber1").receive();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread() {
public void run() {
try {
new TopicMsgSubscriber("subscriber2").receive();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
二、spring api 实现queue生产者、消费者
1、spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
">
<bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory"
destroy-method="stop">
<property name="connectionFactory">
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>failover://(tcp://127.0.0.1:61616)?randomize=false&jms.prefetchPolicy.queuePrefetch=1</value>
</property>
</bean>
</property>
<property name="maxConnections" value="100"></property>
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref local="jmsFactory" />
</property>
</bean>
<bean id="springApiQueue" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg index="0" value="spring-api-queue" />
</bean>
<bean id="springApiQueueMessageListener" class="com.hcb.mq.listener.SpringApiQueueMessageListener"></bean>
<bean id="listenerContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="concurrentConsumers" value="2" />
<property name="connectionFactory" ref="jmsFactory" />
<property name="destination" ref="springApiQueue" />
<property name="messageListener" ref="springApiQueueMessageListener" />
<property name="pubSubNoLocal" value="false"></property>
</bean>
</beans>
2、代码
2.1、生产者
package com.hcb.mq.springapi;
import java.io.IOException;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import com.hcb.mc.vo.User;
import com.hcb.util.JsonUtil;
public class Producer {
public static void main(String[] args) throws JsonGenerationException,
JsonMappingException, IOException, InterruptedException {
AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"mq.xml");
JmsTemplate template = (JmsTemplate) applicationContext
.getBean("jmsTemplate");
Destination subjectDestination = (Destination) applicationContext
.getBean("springApiQueue");
for (int i = 0; i < 5; i++) {
User tmpUser = new User();
tmpUser.setName("张三" + i);
final String tmpMessageText = JsonUtil.toJson(tmpUser);
template.send(subjectDestination, new MessageCreator() {
public Message createMessage(Session session)
throws JMSException {
Message message = session.createTextMessage(tmpMessageText);
return message;
}
});
}
Thread.sleep(10 * 1000);
applicationContext.close();
System.out.println("Producer over");
}
}
2.2、消费者
package com.hcb.mq.listener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SpringApiQueueMessageListener implements MessageListener {
static Logger LOG = LoggerFactory
.getLogger(SpringApiQueueMessageListener.class);
@Override
public void onMessage(Message message) {
String textMsg = null;
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
try {
textMsg = textMessage.getText();
} catch (JMSException e) {
e.printStackTrace();
}
}
LOG.info("SpringApiQueueMessageListener, textMsg: " + textMsg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}