-
Notifications
You must be signed in to change notification settings - Fork 8
/
SimpleProducer.java
64 lines (53 loc) · 2.45 KB
/
SimpleProducer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package org.apache.activemq.simple.queue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
public class SimpleProducer {
private static final Log LOG = LogFactory.getLog(SimpleProducer.class);
private static final Boolean NON_TRANSACTED = false;
private static final long MESSAGE_TIME_TO_LIVE_MILLISECONDS = 0;
private static final int MESSAGE_DELAY_MILLISECONDS = 100;
private static final int NUM_MESSAGES_TO_BE_SENT = 100;
private static final String CONNECTION_FACTORY_NAME = "myJmsFactory";
private static final String DESTINATION_NAME = "queue/simple";
public static void main(String args[]) {
Connection connection = null;
try {
// JNDI lookup of JMS Connection Factory and JMS Destination
Context context = new InitialContext();
ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME);
Destination destination = (Destination) context.lookup(DESTINATION_NAME);
connection = factory.createConnection();
connection.start();
Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(destination);
producer.setTimeToLive(MESSAGE_TIME_TO_LIVE_MILLISECONDS);
for (int i = 1; i <= NUM_MESSAGES_TO_BE_SENT; i++) {
TextMessage message = session.createTextMessage(i + ". message sent");
LOG.info("Sending to destination: " + destination.toString() + " this text: '" + message.getText());
producer.send(message);
Thread.sleep(MESSAGE_DELAY_MILLISECONDS);
}
// Cleanup
producer.close();
session.close();
} catch (Throwable t) {
LOG.error(t);
} finally {
// Cleanup code
// In general, you should always close producers, consumers,
// sessions, and connections in reverse order of creation.
// For this simple example, a JMS connection.close will
// clean up all other resources.
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
LOG.error(e);
}
}
}
}
}