Hello ActiveMq

Common

1
2
3
4
5
6
7
8
9
10
11
12
13
// connection's factory[modle]
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
JMSProducer.USERNAME,
JMSProducer.PASSWORD,
JMSProducer.BROKEURL);
// connection object[don't forget to close it]
Connection connection = connectionFactory.createConnection();
// begin
connection.start();
// communication with MQ[transaction modle, false in consumer]
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
// MQ address object
Destination destination;

close connection in final

1
2
3
4
5
6
7
8
9
finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}

Producer-Consumer

producer

1
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
2
3
4
5
6
7
8
9
10
11
12
13
14
// the queue's name
destination = session.createQueue("HelloWorld");
// the producer object
messageConsumer = session.createConsumer(destination);

while (true) {
// timeout if no response
TextMessage textMessage = (TextMessage) messageConsumer.receive(100000);
if(textMessage != null){
System.out.println("recieved:" + textMessage.getText());
}else {
break;
}
}

Publish-Subscribe

publish

1
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);

subscribe

1
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() {
@Override
public void onMessage(Message message) {
TextMessage tmd = (TextMessage) message;
try {
System.out.println("Received message: " + tmd.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});