Producer.java-------------------------------------------------
package cn.temptation.test;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
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;
public class Producer {
private ConnectionFactory connectionFactory;
private Connection connection;
private Session session;
private MessageProducer producer;
public Producer() {
try {
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER,
ActiveMQConnectionFactory.DEFAULT_PASSWORD, "tcp://loaclhost:61616");
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(Boolean.FALSE, session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(null);
} catch (JMSException e) {
e.printStackTrace();
}
}
public void sendMessage() throws Exception {
Destination destination = session.createTopic("topic1");
TextMessage msg = session.createTextMessage("我是内容");
producer.send(destination, msg);
}
public static void main(String[] args) throws Exception {
Producer p = new Producer();
p.sendMessage();
}
}
Consumer.java-------------------------------------------------------------------------------------------
package cn.temptation.test;
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.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
public class Consumer {
private ConnectionFactory connectionFactory;
private Connection connection;
private Session session;
private MessageConsumer consumer;
public Consumer() {
try {
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER,
ActiveMQConnectionFactory.DEFAULT_PASSWORD, "tcp://loaclhost:61616");
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(Boolean.FALSE, session.AUTO_ACKNOWLEDGE);
consumer = session.createConsumer(null);
} catch (JMSException e) {
e.printStackTrace();
}
}
public void receive() throws Exception {
Destination destination = session.createTopic("topic1");
consumer = session.createConsumer(destination);
consumer.setMessageListener(new Listener());
}
class Listener implements MessageListener {
@Override
public void onMessage(Message message) {
try {
if (message instanceof TextMessage) {
System.out.println("消费者收到------------------");
TextMessage msg = (TextMessage) message;
System.out.println(msg.getText());
}
} catch (JMSException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
Consumer c = new Consumer();
c.receive();
}
}