1 package cn.sinobest.asj.producer.jms.deliverymode;
2 import javax.jms.Connection;
3 import javax.jms.ConnectionFactory;
4 import javax.jms.DeliveryMode;
5 import javax.jms.Destination;
6 import javax.jms.JMSException;
7 import javax.jms.MessageProducer;
8 import javax.jms.Session;
9 import javax.jms.TextMessage;
10 import javax.naming.Context;
11 import javax.naming.InitialContext;
12 import javax.naming.NamingException;
13 import org.junit.Test;
14 /**
15 * 基于不同的Delivery Mode的测试类.
16 * @author lijinlong
17 *
18 */
19 public class ProducerTest {
20 /** JNDI name for ConnectionFactory */
21 static final String CONNECTION_FACTORY_JNDI_NAME = "ConnectionFactory";
22 /** JNDI name for Queue Destination (use for PTP Mode) */
23 static final String QUEUE_JNDI_NAME = "exampleQueue";
24
25 /** deliveryMode */
26 int deliveryMode = DeliveryMode.NON_PERSISTENT;
27
28 /**
29 * 测试持久模式的消息发送.
30 */
31 @Test
32 public void sendPersistent() {
33 setDeliveryMode(DeliveryMode.PERSISTENT);
34 send(QUEUE_JNDI_NAME);
35 }
36
37 /**
38 * 测试非持久模式的消息发送.
39 */
40 @Test
41 public void sendNoPersistent() {
42 setDeliveryMode(DeliveryMode.NON_PERSISTENT);
43 send(QUEUE_JNDI_NAME);
44 }
45
46 public int getDeliveryMode() {
47 return deliveryMode;
48 }
49 private void setDeliveryMode(int deliveryMode) {
50 this.deliveryMode = deliveryMode;
51 }
52 /**
53 * 发送到指定的目的地.
54 *
55 * @param destJndiName
56 * 目的地的JNDI name.
57 */
58 private void send(String destJndiName) {
59 Context jndiContext = null;
60 ConnectionFactory connectionFactory = null;
61 Connection connection = null;
62 Session session = null;
63 Destination destination = null;
64 MessageProducer producer = null;
65 // create a JNDI API IntialContext object
66 try {
67 jndiContext = new InitialContext();
68 } catch (NamingException e) {
69 System.out.println("Could not create JNDI Context:"
70 + e.getMessage());
71 System.exit(1);
72 }
73 // look up ConnectionFactory and Destination
74 try {
75 connectionFactory = (ConnectionFactory) jndiContext
76 .lookup(CONNECTION_FACTORY_JNDI_NAME);
77 destination = (Destination) jndiContext.lookup(destJndiName);
78 } catch (NamingException e) {
79 System.out.println("JNDI look up failed:" + e.getMessage());
80 System.exit(1);
81 }
82 // send Messages and finally release the resources.
83 try {
84 connection = connectionFactory.createConnection();
85 session = connection.createSession(Boolean.FALSE,
86 Session.AUTO_ACKNOWLEDGE);
87 producer = session.createProducer(destination);
88 producer.setDeliveryMode(getDeliveryMode());
89
90 TextMessage message = session.createTextMessage();
91 for (int i = 0; i < 3; i++) {
92 message.setText(String.format("This is the %dth message.",
93 i + 1));
94 producer.send(message);
95 }
96
97 } catch (JMSException e) {
98 e.printStackTrace();
99 } finally {
100 try {
101 if (session != null)
102 session.close();
103 if (connection != null)
104 connection.close();
105 } catch (JMSException e) {
106 e.printStackTrace();
107 }
108 }
109 }
110 }