生产者:
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
public class MyProducer {
private String user = ActiveMQConnection.DEFAULT_USER;
private String password = ActiveMQConnection.DEFAULT_PASSWORD;
private String url = "tcp://localhost:61616";
private String subject = "FUCKWORLD";
private Destination destination;
public void begin() {
Connection connection = null;
try {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
user, password, url);
connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
destination = session.createTopic(subject);
MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
TextMessage message = session.createTextMessage("hello world");
producer.send(message);
} catch (Exception e) {
}
}
}
消费者:
import javax.jms.Connection;
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.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
public class MyConsumer implements MessageListener{
private String user = ActiveMQConnection.DEFAULT_USER;
private String password = ActiveMQConnection.DEFAULT_PASSWORD;
private String url = "tcp://localhost:61616";
private ActiveMQConnectionFactory connectionFactory;
private Connection connection;
private Session session;
private Destination destination;
private String subject = "FUCKWORLD";
private MessageConsumer consumer = null;
public MyConsumer() {
try {
connectionFactory = new ActiveMQConnectionFactory(user, password,
url);
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createTopic(subject);
consumer = session.createConsumer(destination);
consumer.setMessageListener(this);
} catch (JMSException e) {
e.printStackTrace();
}
}
@Override
public void onMessage(Message message) {
TextMessage txtMsg = (TextMessage) message;
try {
System.out.println(txtMsg.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
测试代码:
public class Mytest {
public static void main(String[] args) {
MyConsumer mc = new MyConsumer();
MyProducer mp = new MyProducer();
mp.begin();
}
}