消费者接受消息的方法:
1.第一种方法使用consumer.receive() 或 consumer.receive(int timeout)接受消息,消息的接收者会一直等待下去,直到有消息到达,或者超时。2.第二种方法:消息消费者注册一个MessageListener,当有消息到达的时候,会回调它的onMessage()方法。
第一种方法见:http://blog.youkuaiyun.com/adam_wzs/article/details/51145800
第二种方法见下文,如果不会配置ActiveMQ环境请看第一种方法连接。
ConsumerTool.java
package com.wangzs.t3;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
* @Title 消息消费者工具类
* @Description 消息消费者是由会话创建的一个对象,它用于接收发送到目的地的消息。
* @author wangzs
* @date 2016-4-26
*/
public class ConsumerTool implements MessageListener {
private String user;
private String password;
private String url;
private String queueName; // queueName是一个服务器的queue
private ConnectionFactory connectionFactory = null; // 连接工厂,客户用来创建连接的对象
private Destination destination = null; // 指定它生产的消息的目标和它消费的消息的来源的对象
private Connection connection = null; // 封装了客户与 JMS 提供者之间的一个虚拟的连接
private Session session = null; // 生产和消费消息的一个单线程上下文
private MessageConsumer consumer = null; // 消息消费者
public ConsumerTool() {
super();
}
public ConsumerTool(String user, String password, String url, String queueName) {
super();
this.user = user;
this.password = password;
this.url = url;
this.queueName = queueName;
}
public void initialize() {
connectionFactory = new ActiveMQConnectionFactory(this.getUser(), this.getPassword(), this.getUrl());
try {
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue(this.getQueueName());
consumer = session.createConsumer(destination);
} catch (JMSException e) {
e.printStackTrace();
}
}
// 消费消息
public void consumeMessage() {
System.out.println("Consumer:->Begin listening...");
try {
consumer.setMessageListener(this);
} catch (JMSException e) {
e.printStackTrace();
}
}
@Override
public void onMessage(Message message) {
try {
if (message instanceof TextMessage) {
TextMessage txtMsg = (TextMessage) message;
String msg = txtMsg.getText();
System.out.println("Consumer:->Received: " + msg);
}
} catch (JMSException e) {
e.printStackTrace();
}
}
// 关闭连接
public void close() {
try {
System.out.println("Consumer:->Closing connection");
if (consumer != null) {
consumer.close();
}
if (session != null) {
session.close();
}
if (connection != null) {
connection.close();
}
} catch (JMSException e) {
e.printStackTrace();
}
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getQueueName() {
return queueName;
}
public void setQueueName(String queueName) {
this.queueName = queueName;
}
}
ProducerTool.java
package com.wangzs.t3;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
* @Title 消息生产者工具类
* @Description 消息生产者是由会话创建的一个对象,用于把消息发送到一个目的地
* @author wangzs
* @date 2016-4-26
*/
public class ProducerTool {
private String user;
private String password;
private String url;
private String queueName; // queueName是一个服务器的queue
private ConnectionFactory connectionFactory = null; // 连接工厂,客户用来创建连接的对象
private Destination destination = null; // 指定它生产的消息的目标和它消费的消息的来源的对象
private Connection connection = null; // 封装了客户与 JMS 提供者之间的一个虚拟的连接
private Session session = null; // 生产和消费消息的一个单线程上下文
private MessageProducer producer = null; // 消息生产者
public ProducerTool() {
super();
}
public ProducerTool(String user, String password, String url, String queueName) {
super();
this.user = user;
this.password = password;
this.url = url;
this.queueName = queueName;
}
public void initialize() {
connectionFactory = new ActiveMQConnectionFactory(this.getUser(), this.getPassword(), this.getUrl());
try {
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue(this.getQueueName());
producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);// NON_PERSISTENT:不要求 JMS Producer 持久保存消息。
} catch (JMSException e) {
e.printStackTrace();
}
}
// 发送消息
public void produceMessage(String message) {
try {
TextMessage msg = session.createTextMessage(message);
System.out.println("Producer:->Sending message: " + message);
producer.send(msg);
} catch (JMSException e) {
e.printStackTrace();
}
}
// 关闭连接
public void close() {
try {
System.out.println("Producer:->Closing connection");
if (producer != null) {
producer.close();
}
if (session != null) {
session.close();
}
if (connection != null) {
connection.close();
}
} catch (JMSException e) {
e.printStackTrace();
}
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getQueueName() {
return queueName;
}
public void setQueueName(String queueName) {
this.queueName = queueName;
}
}
JunitTest.java
package com.wangzs.t3;
import org.apache.activemq.ActiveMQConnection;
import org.junit.Test;
/**
* @Title ActiveMQ工具类测试
* @Description
* @author wangzs
* @date 2016-4-26
*/
public class JunitTest {
@Test
public void test1() throws InterruptedException {
ConsumerTool consumer = new ConsumerTool(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD,
ActiveMQConnection.DEFAULT_BROKER_URL, "WangzsQueue");
ProducerTool producer = new ProducerTool(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD,
ActiveMQConnection.DEFAULT_BROKER_URL, "WangzsQueue");
System.out.println(ActiveMQConnection.DEFAULT_BROKER_URL + "------------");
// 消费者
consumer.initialize();
consumer.consumeMessage();
// 生产者
producer.initialize();
for (int i = 0; i < 10; i++) {
Thread.sleep(500);
producer.produceMessage("Hello, world! " + i);
}
}
}
测试结果:
failover://tcp://localhost:61616------------
2016-04-26 14:28:20 DEBUG FailoverTransport:660 - Reconnect was triggered but transport is not started yet. Wait for start to connect the transport.
2016-04-26 14:28:20 DEBUG FailoverTransport:302 - Started.
2016-04-26 14:28:20 DEBUG FailoverTransport:653 - Waking up reconnect task
2016-04-26 14:28:20 DEBUG FailoverTransport:683 - urlList connectionList:[tcp://localhost:61616], from: [tcp://localhost:61616]
2016-04-26 14:28:20 DEBUG FailoverTransport:855 - Attempting connect to: tcp://localhost:61616
2016-04-26 14:28:20 DEBUG WireFormatNegotiator:82 - Sending: WireFormatInfo { version=7, properties={CacheSize=1024, CacheEnabled=true, SizePrefixDisabled=false, MaxInactivityDurationInitalDelay=10000, TcpNoDelayEnabled=true, MaxInactivityDuration=30000, TightEncodingEnabled=true, StackTraceEnabled=true}, magic=[A,c,t,i,v,e,M,Q]}
2016-04-26 14:28:20 DEBUG InactivityMonitor:331 - Using min of local: WireFormatInfo { version=7, properties={CacheSize=1024, CacheEnabled=true, SizePrefixDisabled=false, MaxInactivityDurationInitalDelay=10000, TcpNoDelayEnabled=true, MaxInactivityDuration=30000, TightEncodingEnabled=true, StackTraceEnabled=true}, magic=[A,c,t,i,v,e,M,Q]} and remote: WireFormatInfo { version=7, properties={CacheSize=1024, SizePrefixDisabled=false, TcpNoDelayEnabled=true, MaxInactivityDurationInitalDelay=10000, MaxInactivityDuration=30000, CacheEnabled=true, TightEncodingEnabled=true, StackTraceEnabled=true}, magic=[A,c,t,i,v,e,M,Q]}
2016-04-26 14:28:20 DEBUG WireFormatNegotiator:118 - Received WireFormat: WireFormatInfo { version=7, properties={CacheSize=1024, SizePrefixDisabled=false, TcpNoDelayEnabled=true, MaxInactivityDurationInitalDelay=10000, MaxInactivityDuration=30000, CacheEnabled=true, TightEncodingEnabled=true, StackTraceEnabled=true}, magic=[A,c,t,i,v,e,M,Q]}
2016-04-26 14:28:20 DEBUG WireFormatNegotiator:125 - tcp://localhost/127.0.0.1:61616 before negotiation: OpenWireFormat{version=7, cacheEnabled=false, stackTraceEnabled=false, tightEncodingEnabled=false, sizePrefixDisabled=false}
2016-04-26 14:28:20 DEBUG WireFormatNegotiator:140 - tcp://localhost/127.0.0.1:61616 after negotiation: OpenWireFormat{version=7, cacheEnabled=true, stackTraceEnabled=true, tightEncodingEnabled=true, sizePrefixDisabled=false}
2016-04-26 14:28:20 DEBUG FailoverTransport:865 - Connection established
2016-04-26 14:28:20 INFO FailoverTransport:891 - Successfully connected to tcp://localhost:61616
Consumer:->Begin listening...
2016-04-26 14:28:20 DEBUG FailoverTransport:660 - Reconnect was triggered but transport is not started yet. Wait for start to connect the transport.
2016-04-26 14:28:20 DEBUG FailoverTransport:302 - Started.
2016-04-26 14:28:20 DEBUG FailoverTransport:653 - Waking up reconnect task
2016-04-26 14:28:20 DEBUG FailoverTransport:683 - urlList connectionList:[tcp://localhost:61616], from: [tcp://localhost:61616]
2016-04-26 14:28:20 DEBUG FailoverTransport:855 - Attempting connect to: tcp://localhost:61616
2016-04-26 14:28:20 DEBUG WireFormatNegotiator:82 - Sending: WireFormatInfo { version=7, properties={CacheSize=1024, CacheEnabled=true, SizePrefixDisabled=false, MaxInactivityDurationInitalDelay=10000, TcpNoDelayEnabled=true, MaxInactivityDuration=30000, TightEncodingEnabled=true, StackTraceEnabled=true}, magic=[A,c,t,i,v,e,M,Q]}
2016-04-26 14:28:20 DEBUG InactivityMonitor:331 - Using min of local: WireFormatInfo { version=7, properties={CacheSize=1024, CacheEnabled=true, SizePrefixDisabled=false, MaxInactivityDurationInitalDelay=10000, TcpNoDelayEnabled=true, MaxInactivityDuration=30000, TightEncodingEnabled=true, StackTraceEnabled=true}, magic=[A,c,t,i,v,e,M,Q]} and remote: WireFormatInfo { version=7, properties={CacheSize=1024, SizePrefixDisabled=false, TcpNoDelayEnabled=true, MaxInactivityDurationInitalDelay=10000, MaxInactivityDuration=30000, CacheEnabled=true, TightEncodingEnabled=true, StackTraceEnabled=true}, magic=[A,c,t,i,v,e,M,Q]}
2016-04-26 14:28:20 DEBUG WireFormatNegotiator:118 - Received WireFormat: WireFormatInfo { version=7, properties={CacheSize=1024, SizePrefixDisabled=false, TcpNoDelayEnabled=true, MaxInactivityDurationInitalDelay=10000, MaxInactivityDuration=30000, CacheEnabled=true, TightEncodingEnabled=true, StackTraceEnabled=true}, magic=[A,c,t,i,v,e,M,Q]}
2016-04-26 14:28:20 DEBUG WireFormatNegotiator:125 - tcp://localhost/127.0.0.1:61616 before negotiation: OpenWireFormat{version=7, cacheEnabled=false, stackTraceEnabled=false, tightEncodingEnabled=false, sizePrefixDisabled=false}
2016-04-26 14:28:20 DEBUG WireFormatNegotiator:140 - tcp://localhost/127.0.0.1:61616 after negotiation: OpenWireFormat{version=7, cacheEnabled=true, stackTraceEnabled=true, tightEncodingEnabled=true, sizePrefixDisabled=false}
2016-04-26 14:28:20 DEBUG FailoverTransport:865 - Connection established
2016-04-26 14:28:20 INFO FailoverTransport:891 - Successfully connected to tcp://localhost:61616
Producer:->Sending message: Hello, world! 0
Consumer:->Received: Hello, world! 0
Producer:->Sending message: Hello, world! 1
Consumer:->Received: Hello, world! 1
Producer:->Sending message: Hello, world! 2
Consumer:->Received: Hello, world! 2
Producer:->Sending message: Hello, world! 3
Consumer:->Received: Hello, world! 3
Producer:->Sending message: Hello, world! 4
Consumer:->Received: Hello, world! 4
Producer:->Sending message: Hello, world! 5
Consumer:->Received: Hello, world! 5
Producer:->Sending message: Hello, world! 6
Consumer:->Received: Hello, world! 6
Producer:->Sending message: Hello, world! 7
Consumer:->Received: Hello, world! 7
Producer:->Sending message: Hello, world! 8
Consumer:->Received: Hello, world! 8
Producer:->Sending message: Hello, world! 9
Consumer:->Received: Hello, world! 9