這里單獨列出來我也是覺得有點必要的,畢竟JMS總體知識點並不多,這點可能被很多人所忽視.
首選定義:消息的確認是指消息接受者接到消息,並做出了對應的處理之后,它將回送一個確認消息.
對於非事務性會話,創建會話時應該指定確定方式,JMS定義了3種確認方式:
JMS確認3種方式 | |
Auto_ACKnowledge | 自動通知. |
Client_AcKnowledge | 客戶端自行決定通知時機 這種方式要求客戶端使用javax.jms.Message.acknowledge()方法完成確認. |
Dups_OK_ACKnowledge | 延時//批量通知 這種確認方式允許JMS不必急於確認收到的消息,允許在收到多個消息之后一次完成確認,與Auto_AcKnowledge相比,這種確認方式在某些情況下可能更有效,因為沒有確認,當系統崩潰或者網絡出現故障的時候,消息可以被重新傳遞. |
二:JMS連接創建JMS會話的代碼:
想回看下這段代碼:
01 |
/** |
02 |
* @description 下面是要從服務器上獲取連接工廠的JNDI和隊列地址的JNDI. 然后就是發送信息到服務器端. |
03 |
* @param msg 消息的文本內容 |
04 |
* @param cfJNDI 連接工廠的JNDI |
05 |
* @param queueJNDI 隊列的JNDI |
06 |
* @return 如果成功返回true. |
07 |
* @throws JMSException |
08 |
* @throws NamingException |
09 |
*/ |
10 |
private boolean getConnectFactory(String msg, String cfJNDI, String queueJNDI) throws JMSException, NamingException { |
11 |
Connection connection = null ; |
12 |
MessageProducer producer = null ; |
13 |
try { |
14 |
//初始化上下文 |
15 |
InitialContext ic = new InitialContext(); |
16 |
//JMS客戶端使用JNDI 查找,定位 連接工廠 |
17 |
ConnectionFactory connectionFactory = (ConnectionFactory) ic.lookup(cfJNDI); |
18 |
//PTP模式,使用Queue.JMS客戶端使用JNDI 查找,定位 Queue. |
19 |
Queue queue = (Queue) ic.lookup(queueJNDI); |
20 |
//通過連接工廠,獲取 JMS連接. |
21 |
connection = connectionFactory.createConnection(); |
22 |
//通過JMS連接,獲取到 JMS會話.后面的參數下章或下下章講解. |
23 |
Session session = connection.createSession( false , Session.AUTO_ACKNOWLEDGE); |
24 |
//在JMS會話中,創建一個 JMS消息生產者. |
25 |
producer = session.createProducer(queue); |
26 |
//在JMS會話中,創建Text文本消息. |
27 |
TextMessage message = session.createTextMessage(); |
28 |
message.setText(msg); |
29 |
//發送到JMS目的. |
30 |
producer.send(message); |
31 |
//關閉JMS. |
32 |
this .close(connection, producer); |
33 |
} catch (JMSException e) { |
34 |
this .close(connection, producer); |
35 |
throw new JMSException(e.getMessage()); |
36 |
} catch (NamingException e) { |
37 |
this .close(connection, producer); |
38 |
throw new NamingException(e.getMessage()); |
39 |
} |
40 |
return true ; |
41 |
} |
42 |
43 |
private void close(Connection connection, MessageProducer producer) throws JMSException { |
44 |
try { |
45 |
if ( null != producer) { |
46 |
producer.close(); |
47 |
} |
48 |
if ( null != connection) { |
49 |
connection.close(); |
50 |
} |
51 |
} catch (JMSException e) { |
52 |
throw new JMSException(e.getMessage()); |
53 |
} |
54 |
} |
1 |
//通過JMS連接,獲取到 JMS會話.后面的參數下章或下下章講解. |
2 |
Session session = connection.createSession( false , Session.AUTO_ACKNOWLEDGE); |
上面這句是重點,這段代碼是創建Session時調用了Connection的方法,第一個false參數,是表明會話是否具有事務性.如果是false,必須指定確認方式.