經曆JMS編程

來源:互聯網
上載者:User

http://life-trace.blog.sohu.com/66841260.html

本文是我借鑒網友的資料,通過自己的摸索、實踐而得到,文中應用了網友的部分內容,因為打字實在太累了,呵呵。

<!--[if !supportEmptyParas]--> <!--[endif]-->

一、實踐的環境

XP SP2

weblogicserver811_win32.exe

java_ee_sdk-5_02-windows-nojdk.exe

jdk-1_5_0_06-windows-i586-p.exe

<!--[if !supportEmptyParas]--> <!--[endif]-->

二、軟體的安裝

1)XP的安裝相信大家都會了,這裡就不說了;

2)Weblogic: 首先去www.bea.com下載相應的版本,雙擊可執行檔進行安裝,只要根據嚮導安裝基本就問題不大,預設控制台連接埠號碼是7001,那麼當我們安裝完後,首先配置server domain,可以從QuickStart或者configration wizard中進行配置,配置的時候要記錄下你自己設定的一下配置資訊,如使用者名稱,密碼等,到時進入WEBLOGIC 控制台時要用到,配置完之後從開始->所有程式->bea weblogic platform8.1->user
projects->domain_name->start server啟動伺服器,運行瀏覽器,在地址欄中輸入:http://127.0.0.1:7001/console進入weblogic 控制台,能開到控制台資訊,說明安裝配置成功。

3)j2eesdk:

首先去www.sun.com下載j2eesdk相應版本,雙擊可執行程式進行安裝,按照嚮導即可完成,這裡省略。

4)jdk

這個學習了JAVA的應該熟悉吧,省略

<!--[if !supportEmptyParas]--> <!--[endif]-->

【注意:要在安裝J2EESDK之前安裝jdk】

<!--[if !supportEmptyParas]--> <!--[endif]-->

三、環境變數

這裡假如讀者已經配置好Java的環境變數,在J2EE環境變數配置之前,我們要講講幾個相應的包,第一個是jms.jar,這個包可以在你J2EESDK安裝目錄下的imq\lib下),將這個包COPY到JDK的lib檔案夾下(當然你可以不拷貝過去,可以直接在CLASSPATH中加入這個包的路徑也可以,這裡假如拷貝過去),第二個weblogic.jar,這個包可以在%weblogic_root%/weblogic81/server/lib/中找到,這裡我們直接在CLASSPATH中假如這個包路徑,而不拷貝到JDK的lib檔案夾下,我的環境變數為:

<!--[if !supportEmptyParas]--> <!--[endif]-->

在原有CLASSPATH中添加F:\jdk1.5\lib\jms.jar;.;F:\bea\weblogic81\server\lib\weblogic.jar進去,同時PATH中添加F:\J2EE\bin; ,建立一個J2EE_HOME,值為F:\J2EE,

<!--[if !supportEmptyParas]--> <!--[endif]-->

【注意:如果你的安裝目錄與我的不同,請相應修改】

<!--[if !supportEmptyParas]--> <!--[endif]-->

四、配置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:\BEA\user_projects\domains\mydomain\sendfilestore,點擊"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";

<!--[endif]-->

五. 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:7001

 //注意:weblogic使用t3協議,weblogic我本人使用預設連接埠7001,如果你使用的是其他連接埠,那麼修改成你使用的連接埠號碼,如果你的WEBLOGIC沒有安裝在本機,那麼將localhost改成相應的IP地址即可
串連工廠: 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+"\n");
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:7001
串連工廠: 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)開啟DOS介面. 轉到發送接收程式目錄編譯檔案

2) 執行接受程式;

3). 開啟另一視窗,執行發送程式;

4).從發送端輸入要發送的字元,按ENTER發送,試試,接受端能接收到嗎,如果不行,給我留言吧,我會儘快回覆你的,呵呵(中文也可以哦)

5). 輸入發送訊息"quit",接收程式結束.

<!--[if !vml]--><!--[endif]-->

如果對於上面的內容,你有什麼疑惑,請留言給我吧,我會儘快回覆你的。。。

祝好運!

<!--[if !supportEmptyParas]--> <!--[endif]-->

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.