1、编写消息监听器,监听器继承MessageListener类,代码如下:
package com.wedu.mq;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;
public class MyMessageListener implements MessageListener {
@Override
public void onMessage(Message message) {
if(message instanceof TextMessage) {
TextMessage msg = (TextMessage)message;
try {
System.out.println("receive data:" + msg.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
if(message instanceof ObjectMessage) {
ObjectMessage msg = (ObjectMessage)message;
try {
System.out.println("receive data:" + (Person)msg.getObject());
} catch (JMSException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2、编写消息发送者,代码如下:
package com.wedu.mq;
import javax.jms.Connection;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
import com.wedu.mq.activemq.util.Person;
public class Sender {
public static void main(String[] args) throws Exception {
//创建连接工厂
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
//关闭安全检查,对象序列化
factory.setTrustAllPackages(true);
//创建连接
Connection connection = factory.createConnection();
//打开连接
connection.start();
//创建非事务,自动签收会话
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//创建队列
Queue queue = session.createQueue("MessageListener");
//创建消息的生产者
MessageProducer producer = session.createProducer(queue);
for(int i = 0; i < 10; i++) {
ObjectMessage message = session.createObjectMessage();
Person p = new Person();
p.setName("test" + i);
p.setAge(29);
message.setObject(p);
producer.send(message);
}
producer.close();
session.close();
connection.close();
}
}
3、编写消息接收者,代码如下:
package com.wedu.mq;
import javax.jms.Connection;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
import com.wedu.mq.activemq.util.MyMessageListener;
public class Receiver {
public static void main(String[] args) throws Exception {
//创建连接工厂
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
//关闭安全检查,对象序列化
factory.setTrustAllPackages(true);
//创建连接
Connection connection = factory.createConnection();
//打开连接
connection.start();
//创建非事务,自动签收会话
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//创建队列
Queue queue = session.createQueue("MessageListener");
//创建消息的消费者
MessageConsumer consumer = session.createConsumer(queue);
//注册消息监听器
consumer.setMessageListener(new MyMessageListener());
System.in.read();
consumer.close();
session.close();
connection.close();
}
}
4、启动ActiveMQ服务,然后启动消息接受者和发送者程序,打开队列显示页面,如下图:
控制台输出:
注意:使用监听器,先启动消息接收者监听,在发送消息。