1.首先从网站上下载activemq-web activmq-all jar包
2.发送者代码:
package com.xxx.dispatcher.mq;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* Created with IntelliJ IDEA.
* Date: 14-3-3
* Time: 上午12:40
* To change this template use File | Settings | File Templates.
*/
public class Producer {
public static void main(String[] args) {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnectionFactory.DEFAULT_USER,
ActiveMQConnectionFactory.DEFAULT_PASSWORD,
ActiveMQConnectionFactory.DEFAULT_BROKER_URL);
Connection connection= null;
try {
connection= connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);//发送消息进程
Destination destination = session.createQueue("testQueue");
MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
sendMessage(producer, session);
session.commit();
} catch (JMSException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
if(connection!=null){
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
public static void sendMessage(MessageProducer producer, Session session) {
for (int i = 1; i < 10; ++i) {
try {
TextMessage textMessage = session.createTextMessage("activeMq发送第 " + i + " 条消息");
System.out.println(textMessage.getText());
producer.send(textMessage);
} catch (JMSException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
3.消费者代码:
package com.xxx.dispatcher.mq;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* Created with IntelliJ IDEA.
* Date: 14-3-3
* Time: 上午12:58
* To change this template use File | Settings | File Templates.
*/
public class Customer {
public static void main(String[] args) {
//创建连接工厂,便于创建connection(生产中与消费者通过connection(链接)
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD,
ActiveMQConnectionFactory.DEFAULT_BROKER_URL);
Connection connection = null;
try {
connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("testQueue");
MessageConsumer customer = session.createConsumer(destination);
while (true) {
TextMessage textMessage = (TextMessage) customer.receive(3000);
if (textMessage != null) {
System.out.println("收到消息:" + textMessage.getText());
} else {
break;
}
}
} catch (Exception e) {
} finally {
if (null != connection) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
}