In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to configure JMS". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
one。 Introduction to JMS
1. Basic concepts of JMS
JMS (Java Message Service) is a standard API for accessing enterprise messaging systems. It is convenient for messaging systems.
Unified Java applications exchange messages and simplify the development of enterprise applications by providing standard interfaces for generating, sending and receiving messages.
2. Basic functions of JMS
JMS is an application program interface for communicating with message-oriented middleware. It supports both point-to-point (point-to-point) and publish / subscribe (publish/subscribe) domains, and provides support for the following types: approved messaging, transactional message delivery, consistent messages, and persistent subscriber support. JMS also provides another way to integrate your application with the old back-end system.
3. WebLogic JMS Server introduction
WebLogic Server8.1 conforms to the JAVA specification and is recognized by Sun Microsystems J2EE 1.3
Certificate. As a part of WebLogic, WebLogic JMS Server also fully complies with JMS specification, supports clusters, and can be applied to actual enterprise systems. The following figure shows the WebLogic JMS Server architecture. You can see that the main components of WebLogic JMS Server are: WebLogic JMS servers (for message communication), Java client, JNDI (for domain name lookup), backup storage (for persistent message storage, file-based or JDBC database).
two。 WebLogic JMS characteristics
1. Message communication model
JMS supports two message communication models: point-to-point (point-to-point) (PTP) model and publish / subscribe (Pub/Sub) model. The two message communication models are very similar except for the following differences:
The PTP model specifies that a message can have only one recipient; the Pub/Sub model allows a message to have multiple recipients.
two。 Message composition
The center of the messaging system is the message.
A Message is divided into three components:
? The header is a standard set of fields that both clients and vendors use to identify and route messages.
? Property (property) supports the addition of optional header fields to the message. If your application needs to catalog and classify messages without using standard header fields, you can add an attribute to the message to achieve this cataloging and classification. Provide set
Property (...) And getProperty (...) Method to set and get properties of various Java types, including Object. JMS defines a standard set of attributes that the vendor chooses to provide.
? The body of the message contains the content to be sent to the receiving application. Each message interface is specific to the type of content it supports.
JMS provides their own message types for different types of content, but all messages are derived from the Message interface.
? StreamMessage: contains the Java basic value stream, which is sequentially populated and read with standard stream operations.
? MapMessage: contains a set of name / value pairs; the basic type whose name is string and the value is Java.
? TextMessage: contains a String.
? ObjectMessage: contains a Serializable Java object; a collection class that can use JDK.
? BytesMessage: contains uninterpreted byte streams: encodes the body to match the existing message format.
? XMLMessage: contains XML content. Extend the use of the TextMessage,XMLMessage type to make message filtering very convenient.
3. Message confirmation mode
In a non-transactional session, there are five acknowledgement modes for the session created by the application, while in the transactional session, the acknowledgement mode is ignored.
Five confirmation modes are described:
? AUTO_ACKNOWLEDGE: automatic confirmation mode. Once the method call of the receiver application returns from the processing message, the session object acknowledges the receipt of the message.
? CLIENT_ACKNOWLEDGE: client confirmation mode. The session object relies on the application calling an acknowledge () method on the received message. Once this method is called, the session acknowledges all messages received after the last acknowledgement. This pattern allows the application to receive, process, and acknowledge a batch of messages with a single call. Note: in the administrative console, if the Acknowledge Policy property of the connection factory is set to "Previous", but you want to acknowledge all received messages for a given session, call the acknowledge () method with the last message.
? DUPS_OK_ACKNOWLEDGE: the confirmation mode that allows replicas. Once the method call of the receiving application is returned from the processing message, the session object acknowledges the receipt of the message; repeated acknowledgements are allowed. This model is very effective when you need to consider resource use. Note: if your application cannot handle duplicate messages, you should avoid using this mode. If the initialization attempt to send the message fails, the duplicate message can be re-sent.
? NO_ACKNOWLEDGE: do not confirm the mode. It is necessary not to confirm the message received. After messages are sent to a NO_ACKNOWLEDGE session, they are immediately deleted by the WebLogic server. In this mode, the received message cannot be retrieved and may result in the following results: 1. The message may be lost; and / or in another case: 2. If the initialization attempt to send a message fails, a duplicate message will be sent.
? The non-acknowledgement mode under MULTICAST_NO_ACKNOWLEDGE:IP multicast also does not need to be confirmed. Messages sent to a MULTICAST_NO_ACKNOWLEDGE session share the same characteristics as the NO_ACKNOWLEDGE acknowledgement mode described earlier. This mode supports applications that want to communicate messages through IP multicasting without relying on the quality of service provided by session acknowledgement. Note: if your application cannot handle message loss or repetition, you should avoid using this mode. If the initialization attempt to send the message fails, the duplicate message may be sent again.
Note: among the five confirmation modes in the table above, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE and
CLIENT_ACKNOWLEDGE is defined by the JMS specification, and NO_ACKNOWLEDGE and MULTICAST_NO_ACKNOWLEDGE are provided by WebLogic JMS.
three。 Configure JMS
1. Create a connection factory
(1) start WebLogic Server8.1, log in to the console, select the JMS Connection Factories node, and click "Configure a new JMS Connection Factory..." on the right.
(2) enter the name of the connection factory SendJMSFactory and JNDI name SendJMSFactory, and click "Create"
(3) check "myserver" to apply SendJMSFactory to myserver
two。 Define backup storage
(1) Select the JMS Stores node and click "Configure a new JMS Connection Factory..." on the right
(2) fill in the name SendFileStore and directory Directionary E:BEAuser_projectsdomainsmydomainsendfilestore of the file backup storage, and click "Create".
3. Create a JMS server
(1) Select the JMS Servers node and click "Configure a new JMSServer..." on the right
(2) enter the name of the JMS server SendJMSServer and Paging Store set to "SendFileStore", and click "Create"
(3) Target selects "myserver" to apply SendJMSServer to myserver.
4. Create a message queue
(1) expand the "SendJMSServer" node and click "Configure a new JMS Queue..."
(2) enter the name of the message queue SendJMSQueue and JNDI name SendJMSQueue, and click "Create"
four。 JMS application
A JMS application consists of the following elements:
? JMS client. A Java program that sends and receives messages using JMS API.
? Non-JMS (Non-JMS) client. It's important to realize that older programs often become part of the entire JMS application, and their inclusion should be considered in advance at design time.
? News. The format and content of messages exchanged between JMS and non-JMS clients must be considered in JMS application design.
? JMS vendor. Vendors must provide specific implementations specific to their MOM products.
? Managed object. The administrator of the messaging system vendor creates an object that is independent of the vendor's proprietary technology. Includes the connection factory ConnectionFactory and the destination Destination.
A typical JMS program requires the following steps to start message generation and usage:
? Find ConnectionFactory through JNDI.
? Find one or more Destination through JNDI.
? Create a Connection with ConnectionFactory.
? Create one or more Session with Connection.
? Create the required MessageProducer and MessageConsumer with Session and Destination.
? Start Connection.
The following demonstrates the process of sending and receiving peer-to-peer messages using the JMS resources configured above.
five。 Design the message sender
1. JMS resources used
Server URL: t3://localhost:80
Connection Factory: SendJMSFactory
Queue: SendJMSQueue
two。 Design steps
? Initialize 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)
? Create Connection with ConnectionFactory
Qcon = qconFactory.createQueueConnection ()
? Create a Session with Connection
Qsession = qcon.createQueueSession (false, Session.AUTO_ACKNOWLEDGE)
? Create MessageProducer with Session and Destination
Qsender = qsession.createSender (queue)
? Start Connection.
Qcon.start ()
? Send a message
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 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)
}
}
six。 Design the message receiver
1. JMS resources used
Server URL: t3://localhost:80
Connection Factory: SendJMSFactory
Queue: SendJMSQueue
two。 Design steps
? Initialize 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)
? Create Connection with ConnectionFactory
Qcon = qconFactory.createQueueConnection ()
? Create a Session with Connection
Qsession = qcon.createQueueSession (false, Session.AUTO_ACKNOWLEDGE)
? Create MessageConsumer with Session and Destination
Qreceiver = qsession.createReceiver (queue)
? Set up snooping
Qreceiver.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 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)
}
}
seven。 Test message sending and receiving
1. Set up WebLogic Classpath
two。 Go to the send and receive program directory compilation file
3. Execute the acceptance procedure
4. Open another window and execute the sender
5. Enter the send message "quit" and the receiver ends.
This is the end of "how to configure JMS". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.