Through JMS Programming

Source: Internet
Author: User
Tags qcon

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

This article draws on the information of netizens and gets it through self-exploration and practice. Some content of netizens is applied in this article because typing is too tired.

<! -- [If! Supportemptyparas] --> <! -- [Endif] -->

I. Practice Environment

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] -->

Ii. Software Installation

1) I believe everyone will install XP. I won't talk about it here;

2) WebLogic: first download the corresponding version from www.bea.com and double-click the executable file to install it. As long as the Wizard is installed, the problem is not serious. The default Console port number is 7001, after the installation is complete, first Configure the server domain, which can be configured from Quickstart or configration wizard. During configuration, record the configuration information you set yourself, such as the user name, password, etc. It will be used when you enter the Weblogic console. After configuration, start from-> All Programs-> BEA WebLogic platform8.1-> User
Projects-> domain_name-> Start Server start the server and run the browser. in the address bar, enter http: // 127.0.0.1: 7001/console to enter the Weblogic console, which can be opened to the console information, the configuration is successfully installed.

3) j2eesdk:

First download the corresponding j2eesdk version at www.sun.com, double-click the executable program to install it, and follow the wizard.

4) JDK

I should be familiar with Java.

<! -- [If! Supportemptyparas] --> <! -- [Endif] -->

[Note: Install JDK before j2eesdk]

<! -- [If! Supportemptyparas] --> <! -- [Endif] -->

Iii. Environment Variables

If you have configured Java environment variables, let's talk about several corresponding packages before configuring J2EE environment variables. The first one is JMS. jar, this package can be under imq \ Lib under your j2eesdk installation directory), copy this package to the JDK lib folder (of course, you can not copy it in the past, you can also directly add the path of this package to classpath. If you copy it here), the second weblogic. jar, this package can be found in % weblogic_root %/weblogic81/Server/lib/. Here we will directly assume this package path in classpath without copying it to the JDK lib folder, my environment variables are:

<! -- [If! Supportemptyparas] --> <! -- [Endif] -->

Add F: \ jdk1.5 \ Lib \ JMS to the original classpath. jar ;.; f: \ Bea \ weblogic81 \ Server \ Lib \ weblogic. add F: \ J2EE \ bin; to the path, and create a j2ee_home with the value F: \ J2EE,

<! -- [If! Supportemptyparas] --> <! -- [Endif] -->

[NOTE: If your installation directory is different from mine, modify it accordingly]

<! -- [If! Supportemptyparas] --> <! -- [Endif] -->

4. Configure JMS
1. Create a connection Factory
(1) Start WebLogic server8.1, log on to the console, select the JMS connection factories node, and click "configure a new JMS connection factory..." on the right ...";

(2) enter the connection factory name sendjmsfactory and JNDI name sendjmsfactory, and click "CREATE ";

(3) Hook "myserver" and apply sendjmsfactory to myserver;

2. Define backup storage
(1) Select the JMS stores node and click "configure a new JMS connection factory..." on the right ...";

(2) enter the file backup storage name sendfilestore and directory direary ary E: \ Bea \ user_projects \ Domains \ mydomain \ sendfilestore, and click "CREATE ".

3. Create a JMS Server
(1) Select the JMS servers node and click "configure a new jmsserver..." on the right ...";

(2) Set sendjmsserver and paging store to "sendfilestore" and click "CREATE ";

(3) Select "myserver" for target and apply sendjmsserver to myserver.

4. Create a Message Queue
(1) Expand the "sendjmsserver" node and click "configure a new JMS queue ...";

(2) enter the Message Queue name sendjmsqueue and JNDI name sendjmsqueue, and click "CREATE ";

<! -- [Endif] -->

5. JMS Application
A jms application consists of the following elements:
· JMS client. Java program that uses the jms api to send and receive messages.
· Non-JMS clients. Recognizing this is important-old programs often become part of the entire JMS application and their inclusion should be pre-designed.
· Message. The format and content of the messages exchanged between JMS and non-JMS clients are part of the JMS application design.
· JMS supplier. Suppliers must provide specific implementations specific to their mom products.
· Managed object. The Administrator of the supplier of the message passing system creates an object independent of the proprietary vendor technology. Including connection factory connectionfactory and destination.
A typical JMS program requires the following steps to start message generation and use:
· Use JNDI to find connectionfactory.
· Use JNDI to find one or more destinations.
· Use connectionfactory to create a connection.
· Use connection to create one or more sessions.
· Use session and destination to create the required messageproducer and messageconsumer.
· Start connection.
The following describes the process of sending and receiving point-to-point messages using the configured JMS resources.

5. design the message sender
1. JMS resources used
Server URL: T3: // localhost: 7001

// Note: Weblogic uses the T3 protocol. WebLogic uses the default port 7001. If you are using another port, change it to the port number you are using, if your WebLogic is not installed on the local machine, change localhost to the corresponding IP address.
Connection Factory: sendjmsfactory
Queue: sendjmsqueue
2. Design Steps
· Initialize the 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 );
· Use connectionfactory to create a connection
Qcon = qconfactory. createqueueconnection ();
· Use connection to create a session
Qsession = qcon. createqueuesession (false, session. auto_acknowledge );
· Use session and destination to create messageproducer
Qsender = qsession. createsender (Queue );
· Start connection.
Qcon. Start ();
· Send messages
MSG = qsession. createtextmessage ();
MSG. settext (Message );
Qsender. Send (MSG );
3. Source Code
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
* 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;
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 specified med
* @ 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 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 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. Pipeline signorecase ("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 );
}

}

6. design the Message Receiver
1. JMS resources used
Server URL: T3: // localhost: 7001
Connection Factory: sendjmsfactory
Queue: sendjmsqueue
2. Design Steps
· Initialize the 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 );
· Use connectionfactory to create a connection
Qcon = qconfactory. createqueueconnection ();
· Use connection to create a session
Qsession = qcon. createqueuesession (false, session. auto_acknowledge );
· Use session and destination to create messageconsumer
Qreceiver = qsession. createreceiver (Queue );
· Set listeners
Qcycler. setmessagelistener (this );
· Start connection
Qcon. Start ();
3. Source Code
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
* And receive messages from a JMS queue. The classes in this
* Package operate on the same JMS queue. Run the classes together
* 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;
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 ed:" + msgtext );

If (msgtext. equalsignorecase ("quit ")){
Synchronized (this ){
Quit = true;
This. policyall (); // policy main thread to quit
}
}
} Catch (jmsexception jmse ){
Jmse. printstacktrace ();
}
}

/**
* Creates all the necessary objects for processing ing
* Messages from a JMS queue.
*
* @ Param ctx jndi initial context
* @ Param queuename name of queue
* @ Exception namingexception if operation cannot be specified med
* @ 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 );
Qcycler. setmessagelistener (this );
Qcon. Start ();
}

/**
* Closes JMS objects.
* @ Exception jmsexception if JMS fails to close objects due to internal error
*/
Public void close () throws jmsexception
{
Qcycler. Close ();
Qsession. Close ();
Qcon. Close ();
}
/**
* Main () method.
*
* @ Param ARGs WebLogic Server URL
* @ 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 ed.
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 );
}
}
7.Test message sending and receiving


1) Open the DOS interface and go to the sending and receiving program directory to compile the file.

2) execute the acceptance program;

3) open another window and execute the sending program;

4 ). enter the character to be sent from the sender and press enter to send the message. Can the receiver receive the message? If not, leave a message for me and I will reply to you as soon as possible, haha (Chinese can also be used)

5) input the sending message "quit" and the receiving program ends.

<! -- [If! VML] --> <! -- [Endif] -->

If you have any questions about the above content, please leave a message and I will reply to you as soon as possible...

Good luck!

<! -- [If! Supportemptyparas] --> <! -- [Endif] -->

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.