BEA WebLogic Server8.1 JMS入門

一. JMS簡介
1. JMS基本概念
JMS(Java Message Service)是訪問企業消息系統的標準API,它便於消息系
統中的Java應用程序進行消息交換,並且通過提供標準的產生、發送、接收消息的接口簡化企業應用的開發。

2. JMS基本功能
JMS是用於和麪向消息的中間件相互通信的應用程序接口。它既支持點對點(point-to-point)的域,又支持發佈/訂閱(publish/subscribe)類型的域,並且提供對下列類型的支持:經認可的消息傳遞,事務型消息的傳遞,一致性消息和具有持久性的訂閱者支持。JMS還提供了另一種方式來對您的應用與舊的後臺系統相集成。
3. WebLogic JMS Server介紹
WebLogic Server8.1符合JAVA規範,並通過Sun Microsystems J2EE 1.3認
證.作爲WebLogic的一部分,當然WebLogic JMS Server也完全遵從JMS規範,還支持集羣,並可以應用於實際企業系統.下圖是WebLogic JMS Server體系結構.圖中可以看到WebLogic JMS Server主要組件有: WebLogic JMS servers(用於消息通信),Java客戶端,JNDI(用於域名查找), 後備存儲(用於持久消息存儲,基於文件或者JDBC數據庫).

二. WebLogic JMS特性
1. 消息通信模型
JMS 支持兩種消息通信模型:點到點(point-to-point)(PTP)模型和發佈/訂閱(Pub/Sub)模型。除了下列不同之外,這兩種消息通信模型非常地相似:
PTP 模型規定了一個消息只能有一個接收者;Pub/Sub 模型允許一個消息可以有多個接收者。
2. 消息組成
消息傳遞系統的中心就是消息。
一條 Message 分爲三個組成部分:
? 頭(header)是個標準字段集,客戶機和供應商都用它來標識和路由消息。
? 屬性(property)支持把可選頭字段添加到消息。如果您的應用程序需要不使用標準頭字段對消息編目和分類,您就可以添加一個屬性到消息以實現這個編目和分類。提供 set<Type>Property(...) 和 get<Type>Property(...) 方法以設置和獲取各種 Java 類型的屬性,包括 Object。JMS 定義了一個供應商選擇提供的標準屬性集。
? 消息的主體(body)包含要發送給接收應用程序的內容。每個消息接口特定於它所支持的內容類型。
JMS 爲不同類型的內容提供了它們各自的消息類型,但是所有消息都派生自 Message 接口。
? StreamMessage:包含 Java 基本數值流,用標準流操作來順序的填充和讀取。
? MapMessage:包含一組名/值對;名稱爲 string 類型,而值爲 Java 的基本類型。
? TextMessage:包含一個 String。
? ObjectMessage:包含一個 Serializable Java 對象;能使用 JDK 的集合類。
? BytesMessage:包含未解釋字節流: 編碼主體以匹配現存的消息格式。
? XMLMessage: 包含XML內容。擴展TextMessage,XMLMessage 類型的使用,使得消息過濾非常便利。
3. 消息確認模式
非事務性會話中,應用程序創建的會話有5 種確認模式,而在事務性會話中,確認模式被忽略。
五種確認模式說明:
? AUTO_ACKNOWLEDGE:自動確認模式。一旦接收方應用程序的方法調用從處理消息處返回,會話對象就會確認消息的接收。
? CLIENT_ACKNOWLEDGE:客戶端確認模式。會話對象依賴於應用程序對被接收的消息調用一個acknowledge()方法。一旦這個方法被調用,會話會確認最後一次確認之後所有接收到的消息。這種模式允許應用程序以一個調用來接收,處理並確認一批消息。注意:在管理控制檯中,如果連接工廠的Acknowledge Policy(確認方針)屬性被設置爲"Previous"(提前),但是你希望爲一個給定的會話確認所有接收到的消息,那麼就用最後一條消息來調用acknowledge()方法。
? DUPS_OK_ACKNOWLEDGE:允許副本的確認模式。一旦接收方應用程序的方法調用從處理消息處返回,會話對象就會確認消息的接收;而且允許重複確認。在需要考慮資源使用時,這種模式非常有效。注意:如果你的應用程序無法處理重複的消息的話,你應該避免使用這種模式。如果發送消息的初始化嘗試失敗,那麼重複的消息可以被重新發送。
? NO_ACKNOWLEDGE:不確認模式。不確認收到的消息是需要的。消息發送給一個NO_ACKNOWLEDGE 會話後,它們會被WebLogic 服務器立即刪除。在這種模式下,將無法重新獲得已接收的消息,而且可能導致下面的結果:1. 消息可能丟失;和(或者)另一種情況:2. 如果發送消息的初始化嘗試失敗,會出現重複消息被髮送的情況。
? MULTICAST_NO_ACKNOWLEDGE:IP組播下的不確認模式,同樣無需確認。發送給一個MULTICAST_NO_ACKNOWLEDGE會話的消息, 會共享之前所述的NO_ACKNOWLEDGE 確認模式一樣的特徵。這種模式支持希望通過IP 組播方式進行消息通信的應用程序,而且無需依賴會話確認提供的服務質量。注意:如果你的應用程序無法處理消息的丟失或者重複,那麼你應該避免使用這種模式。如果發送消息的初始化嘗試失敗的話,重複的消息可能會被再次發送。
注:在上表的5 種確認模式中,AUTO_ACKNOWLEDGE ,DUPS_OK_ACKNOWLEDGE 和
CLIENT_ACKNOWLEDGE 是JMS 規範定義的,NO_ACKNOWLEDGE 和MULTICAST_NO_ACKNOWLEDGE是WebLogic JMS 提供的。
三. 配置JMS
1. 創建連接工廠
(1) 啓動WebLogic Server8.1,登錄控制檯,選中JMS Connection Factories節點,點擊右邊的" Configure a new JMS Connection Factory...";

(2) 填寫連接工廠的名稱SendJMSFactory和JNDI名稱SendJMSFactory,點擊"Create";

(3) 勾上"myserver",將SendJMSFactory應用到myserver;

2. 定義後備存儲
(1) 選中JMS Stores節點,點擊右邊的" Configure a new JMS Connection Factory...";

(2) 填寫文件後備存儲的名稱SendFileStore和目錄Directionary E:BEAuser_projectsdomainsmydomainsendfilestore,點擊"Create".

3. 創建JMS服務器
(1) 選中JMS Servers節點,點擊右邊的" Configure a new JMSServer...";

(2) 填寫JMS服務器的名稱SendJMSServer和Paging Store設爲" SendFileStore",點擊"Create";

(3) Target選中"myserver",將SendJMSServer應用到myserver.

4. 創建消息隊列
(1) 展開"SendJMSServer"節點,點擊" Configure a new JMS Queue...";

(2) 填寫消息隊列的名稱SendJMSQueue和JNDI名稱SendJMSQueue,點擊"Create";

四. JMS應用程序
一個 JMS 應用程序由下列元素組成:
? JMS 客戶機。 用 JMS API 發送和接收消息的 Java 程序。
? 非 JMS(Non-JMS)客戶機。 認識到這一點很重要 - 舊的程序經常成爲整個 JMS 應用程序的一部分,而且它們的包含應該在設計時預先考慮。
? 消息。 在 JMS 和非 JMS 客戶機之間交換的消息的格式和內容是 JMS 應用程序設計所必須考慮的部分。
? JMS 供應商。供應商必須提供特定於其 MOM 產品的具體的實現。
? 受管對象。 消息傳遞系統供應商的管理員創建了一個對象,它獨立於供應商專有的技術。包括連接工廠ConnectionFactory和目的Destination。
一種典型的 JMS 程序需要經過下列步驟才能開始消息產生和使用:
? 通過 JNDI 查找 ConnectionFactory。
? 通過 JNDI 查找一個或多個 Destination。
? 用 ConnectionFactory 創建一個 Connection。
? 用 Connection 創建一個或多個 Session。
? 用 Session 和 Destination 創建所需的 MessageProducer 和 MessageConsumer。
? 啓動 Connection。
下面利用上面配置的JMS資源演示點對點消息發送和接收的過程。
五. 設計消息發送端
1. 使用的JMS資源
服務器URL: t3://localhost:80
連接工廠: SendJMSFactory
隊列: SendJMSQueue
2. 設計步驟
? 初始化JNDI Tree
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, PROVIDER_URL);
return new InitialContext(env);
? lookup ConnectionFactory
qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
? lookup Destination
queue = (Queue) ctx.lookup(queueName);
? 用 ConnectionFactory 創建Connection
qcon = qconFactory.createQueueConnection();
? 用 Connection 創建一個Session
qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
? 用 Session 和 Destination 創建MessageProducer
qsender = qsession.createSender(queue);
? 啓動 Connection。
qcon.start();
? 發送消息
msg = qsession.createTextMessage();
msg.setText(message);
qsender.send(msg);
3. 源代碼
package jmssample;

import java.util.Hashtable;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/** This example shows how to establish a connection
* and send messages to the JMS queue. The classes in this
* package operate on the same JMS queue. Run the classes together to
* witness messages being sent and received, and to browse the queue
* for messages. The class is used to send messages to the queue.
*
* @author Copyright (c) 1999-2003 by BEA Systems, Inc. All Rights Reserved.
*/
public class QueueSend
{
// Defines the JNDI context factory.
public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";

// Defines the JNDI provider url.
public final static String PROVIDER_URL=" t3://localhost:80";

// Defines the JMS connection factory for the queue.
public final static String JMS_FACTORY="SendJMSFactory";

// Defines the queue.
public final static String QUEUE="SendJMSQueue";


private QueueConnectionFactory qconFactory;
private QueueConnection qcon;
private QueueSession qsession;
private QueueSender qsender;
private Queue queue;
private TextMessage msg;

/**
* Creates all the necessary objects for sending
* messages to a JMS queue.
*
* @param ctx JNDI initial context
* @param queueName name of queue
* @exception NamingException if operation cannot be performed
* @exception JMSException if JMS fails to initialize due to internal error
*/
public void init(Context ctx, String queueName)
throws NamingException, JMSException
{
qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
qcon = qconFactory.createQueueConnection();
qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
queue = (Queue) ctx.lookup(queueName);
qsender = qsession.createSender(queue);
msg = qsession.createTextMessage();
qcon.start();
}

/**
* Sends a message to a JMS queue.
*
* @param message message to be sent
* @exception JMSException if JMS fails to send message due to internal error
*/
public void send(String message) throws JMSException {
msg.setText(message);
qsender.send(msg);
}

/**
* Closes JMS objects.
* @exception JMSException if JMS fails to close objects due to internal error
*/
public void close() throws JMSException {
qsender.close();
qsession.close();
qcon.close();
}
/** main() method.
*
* @param args WebLogic Server URL
* @exception Exception if operation fails
*/
public static void main(String[] args) throws Exception {
InitialContext ic = getInitialContext();
QueueSend qs = new QueueSend();
qs.init(ic, QUEUE);
readAndSend(qs);
qs.close();
}

private static void readAndSend(QueueSend qs)
throws IOException, JMSException
{
BufferedReader msgStream = new BufferedReader(new InputStreamReader(System.in));
String line=null;
boolean quitNow = false;
do {
System.out.print("Enter message ("quit" to quit): ");
line = msgStream.readLine();
if (line != null && line.trim().length() != 0) {
qs.send(line);
System.out.println("JMS Message Sent: "+line+" ");
quitNow = line.equalsIgnoreCase("quit");
}
} while (! quitNow);

}

private static InitialContext getInitialContext()
throws NamingException
{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, PROVIDER_URL);
return new InitialContext(env);
}

}

六. 設計消息接收端
1. 使用的JMS資源
服務器URL: t3://localhost:80
連接工廠: SendJMSFactory
隊列: SendJMSQueue
2. 設計步驟
? 初始化JNDI Tree
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, PROVIDER_URL);
return new InitialContext(env);
? lookup ConnectionFactory
qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
? lookup Destination
queue = (Queue) ctx.lookup(queueName);
? 用 ConnectionFactory 創建Connection
qcon = qconFactory.createQueueConnection();
? 用 Connection 創建一個Session
qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
? 用 Session 和 Destination 創建MessageConsumer
qreceiver = qsession.createReceiver(queue);
? 設置監聽
qreceiver.setMessageListener(this);
? 啓動 Connection
qcon.start();
3. 源代碼
package jmssample;

import java.util.Hashtable;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Hashtable;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
* This example shows how to establish a connection to
* and receive messages from a JMS queue. The classes in this
* package operate on the same JMS queue. Run the classes together to
* witness messages being sent and received, and to browse the queue
* for messages. This class is used to receive and remove messages
* from the queue.
*
* @author Copyright (c) 1999-2003 by BEA Systems, Inc. All Rights Reserved.
*/
public class QueueReceive implements MessageListener
{
// Defines the JNDI context factory.
public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";

// Defines the JNDI provider url.
public final static String PROVIDER_URL=" t3://localhost:80";

// Defines the JMS connection factory for the queue.
public final static String JMS_FACTORY="SendJMSFactory";

// Defines the queue.
public final static String QUEUE="SendJMSQueue";

private QueueConnectionFactory qconFactory;
private QueueConnection qcon;
private QueueSession qsession;
private QueueReceiver qreceiver;
private Queue queue;
private boolean quit = false;

/**
* Message listener interface.
* @param msg message
*/
public void onMessage(Message msg)
{
try {
String msgText;
if (msg instanceof TextMessage) {
msgText = ((TextMessage)msg).getText();
} else {
msgText = msg.toString();
}

System.out.println("Message Received: "+ msgText );

if (msgText.equalsIgnoreCase("quit")) {
synchronized(this) {
quit = true;
this.notifyAll(); // Notify main thread to quit
}
}
} catch (JMSException jmse) {
jmse.printStackTrace();
}
}

/**
* Creates all the necessary objects for receiving
* messages from a JMS queue.
*
* @param ctx JNDI initial context
* @param queueName name of queue
* @exception NamingException if operation cannot be performed
* @exception JMSException if JMS fails to initialize due to internal error
*/
public void init(Context ctx, String queueName)
throws NamingException, JMSException
{
qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
qcon = qconFactory.createQueueConnection();
qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
queue = (Queue) ctx.lookup(queueName);
qreceiver = qsession.createReceiver(queue);
qreceiver.setMessageListener(this);
qcon.start();
}

/**
* Closes JMS objects.
* @exception JMSException if JMS fails to close objects due to internal error
*/
public void close()throws JMSException
{
qreceiver.close();
qsession.close();
qcon.close();
}
/**
* main() method.
*
* @param args WebLogic Server URL
* @exception Exception if execution fails
*/

public static void main(String[] args) throws Exception {

InitialContext ic = getInitialContext();
QueueReceive qr = new QueueReceive();
qr.init(ic, QUEUE);

System.out.println("JMS Ready To Receive Messages (To quit, send a "quit" message).");

// Wait until a "quit" message has been received.
synchronized(qr) {
while (! qr.quit) {
try {
qr.wait();
} catch (InterruptedException ie) {}
}
}
qr.close();
}

private static InitialContext getInitialContext()
throws NamingException
{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, PROVIDER_URL);
return new InitialContext(env);
}


}
七. 測試消息發送和接收
1. 設置WebLogic Classpath;



2. 轉到發送接收程序目錄編譯文件;

3. 執行接受程序;
4. 打開另一窗口,執行發送程序;


5. 輸入發送消息"quit",接收程序結束.


總結
本文先簡要介紹了JMS的一些基本概念,繼而引入了WebLogic JMS Server的體系結構和相關特性。在此基礎之上,圖文並茂地講述了JMS在WebLogic Server 8.1上的配置。最後在解剖JMS應用程序框架的同時,以點對點爲例演示了JMS的發送接收消息流程。
 
發佈了44 篇原創文章 · 獲贊 4 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章