Common
1 | // connection's factory[modle] |
close connection in final1
2
3
4
5
6
7
8
9finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
Producer-Consumer
producer1
2
3
4
5
6
7
8// the queue's name
destination = session.createQueue("HelloWorld");
// the producer object
MessageProducer messageProducer = session.createProducer(destination);
// message
TextMessage message = session.createTextMessage("Hello ActiveMQ");
// send
messageProducer.send(message);
consumer
1 | // the queue's name |
Publish-Subscribe
publish1
2
3
4
5
6
7
8
9
10// give a topic
Topic topic = session.createTopic("HelloTopic");
// message
TextMessage message = session.createTextMessage("ActiveMQ Topic");
// sender
MessageProducer producer = session.createProducer(topic);
// set tmp data
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// publish
producer.send(message);
subscribe1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16// got a topic
Topic topic = session.createTopic("HelloTopic");
// reciever
MessageConsumer consumer = session.createConsumer(topic);
// set a listener, deal callback
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
TextMessage tmd = (TextMessage) message;
try {
System.out.println("Received message: " + tmd.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});