Actual combat JMS (transfer)

xiaoxiao2021-03-06  50

Recently, a Message Driven Bean implemented asynchronous computing function, I hope that I can share friends with MDB or JMS development after organizing.

This is part of a MIS system for calculating the final fee amount. Due to the calculation process and complexity, the implementation does not affect the user interface response, it is to implement asynchronous calculations, and can handle multiple computing requests, and the notification after the calculation Calculate the client of the command. The function is very simple, as long as one MDB can be implemented, but to notify the client calculation to end make the system become more interesting.

JMS API

We first looked with some concepts of JMS before using the system design. JMS derived from the needs of the enterprise application for the message middleware, so that the application can do not affect each other through messages. The JMS application has four components: JMS service provider, message management object, message producer consumers and messages itself.

l JMS service provider implements message queue and notification while implementing the API of message management. JMS is already part of the J2EE API, and J2EE servers provide JMS services.

l Message Management Object provides an API that operates on a message. There are two messaging management objects in the JMS API: ConnectionFactory and Destination, different connectionFactory, depending on the consumption method of the message, can be divided into QueueConnectionFactory and TopicConnectionFactoryFactory, Destination can be divided into Queue and Topic. Use these two management objects to create a session of the message service.

l Measters and consumers of the message. They can be unhesed, only consumers who need messages know how to use messages. Depending on the number of news consumer, the consumer of the message is divided into two categories: Subscriber and Receiver, the same message sender is divided into two categories: Publisher and Sender.

l message. JMS API specifies five messages: Message, MapMessage, TextMessage, ByteMessage, StreamMessage and ObjectMessage

The different form of consumption causes JMS to have two sets of parallel APIs, which is the PTP (Point to Point) model and Pub / Sub (publisher and subscriber, publishing and subscription) models. One message in PTP's message application has only one consumer, and the message is no longer valid after consumption. One message in the Pub / Sub application can have multiple subscribers, and each subscriber is not necessarily to process the message.

Below is the basic model of the JMS application:

(This figure is from Sun's online document JMS Tutorial)

List in the JMS in JMS according to this model:

l QueueConnectionFactory and TopicConnectionFactory Connection Factory To generate instances of QueueConnection and TopicConnection

l QueueConnection and TopicConnection connection objects are used to establish a connection to JMS and generate a session instance

l QueueESession and TopicSession session objects are used to create messages, consumers of producers and messages (explaining the producer of the message: It does not represent the object generated by the message instance, but refers to the object sent to the JMS)

l Queuesender, TopicPublisher, and QueueReciever, TopicsUbscriber. Messages producers and consumers, Queuesender's Send methods, and TopicPublisher's Publish method send messages to Destination. QueueReciever and TopicsUbscriber directly use the methods defined in the parent interface MessageConsumer to receive messages, and setMessageListener methods to set the message listener. QueueReciever's getQueue method gets queeue reference, and the GetTopic method for TopicsBscriber gets Topic references. l MessageListener, message listener. The change interface has only one way onMessage (), and the method has only one message type parameter. After registration through the setMessageListener method of MessageConsumer (QueueReciever and Topicscriber), the system is registered after receiving the message.

l Queue and Topic, Message Destination. The main role is to store messages.

design

The system is too simple to design, simply explain the software's operating environment and execution process, this MIS system is B / S mode, Web Browser will send a message to send a message after completing the addition of the execution task (saved to the database). The calculation process is implemented as MDB. After the calculation is completed, the message will be sent to the web browser that generates task. Don't think that I can really do this, the active put the message to the Web Browser author, there is no this copy. Substance, here uses a way to use an applet, the applet itself is also a running thread, and accesses the received message every other time, if there is a message, the user is prompted. This servlet is a messageconsumer, and MDB is MessageProducer. When the execution task is generated, the JSP / servlet that saves the task is MessageProducer, and the EJB Container running MDB is MessageCunsumer, and MDB becomes a message listener. Because there are two kinds of messages to lazy use two destination (with the above picture, haha), a message for storing the task, a message for storing task completion. Specifically, it is of course the design and implementation of the message content, but it does not affect the system structure, it is not nonsense.

The development tool is JBuilder and WebLogic.

Handoff

1. Send and receive messages. There are three places that need to be manually encoded using JMS API to implement the send and receive messages: send messages, servlets that receive messages, and send calculations for MessageDriveNbean. For the QueueConnectionFactory, QueueConnection, Queue, and QueueUeconnection, Queue, and QueueSession, which are required to send and receive messages, use servlet and MDB lifecycle methods, and obtain resources in the servlet's init method and MDB's EJBCREATE method, and create the need. The resource is released in the EJBREMOVE method of the servlet.

Get resource:

Public void init () throws servletexception {

Try {

InputStream in = this.getClass (). GetClass (). GetClassLoader (). GetResourceAsStream ("JNDI.Properties");

Properties P = new profment ();

p.Load (in);

CTX = New InitialContext (P);

} catch (exception ex) {

EX.PrintStackTrace ();

}

Try {

CONNECTIONFAACTORY = (QueueConnectionFactory) CTX.lookup

ConnectionFactoryName);

Queue = (queue) ctx.lookup (queuename);

Connection = (javax.jms.queueConnection) (QueueConnectionFactory)

ConnectionFactory).

CREATEQUECONNECTION ();

QueueESession = ((javax.jms.queueConnection) Connection.

CreateQueESession (false, session.auto_acknowledge);

Queuesender = quenession.createsender (queue);

} catch (exception ex) {

EX.PrintStackTrace ();

}

Send Message}: public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String taskid = request.getParameter ( "taskid"); try {String completedmsg = "Tasks" taskid "execution is complete"; ObjectMessage om = QueueESession.CreateObjectMessage (NEW CALCULATECOMPLED (UserID, TaskId); Queuesender.send (om);} catch (exception ex) {ex.printStackTrace ();}} receives the message. Here is the message in servlet, and Messages is a HashTable object.

public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {boolean rflag = true; try {messageConsumer = (QueueReceiver) queueSession.createReceiver (queue); connection.start (); while (rflag) {Message m = messageConsumer. receiveNoWait (); if (m = null!) {if (m instanceof ObjectMessage) {ObjectMessage message = (ObjectMessage) m; MessageBody mb = (MessageBody) message.getObject (); ArrayList a = (ArrayList) messages.get (mb .getuserid ()); if (a == null) {a = new arraylist (); a.add (mb); messages.put (mb.getuserid (), a);} else {a.add (MB) }} Else {rflag = false;}} else {rflag = false;}} connection.stop ();} catch (jmsexception e) {E.PrintStackTrace ();}} release resources: public void destr } {try {if (connection! = null) Connection.Close ();} catch (exception ex) {ex.printStackTrace ();}}}} MDB Jebcreate method, like the content of the INIT method, EJBREMOVE and DESTROY The content of the method is the same. The calculation process of MDB is implemented in the onMessage () method, and a message is sent after the calculation is completed. The process of sending messages is already in the process, and will not be described again. 2. WebLogic JMS service configuration. Here, the simplest JMS configuration here, except for the name and JNDI names, the default value is used. a) Start WebLogic, open Web Console B) Expand the JMS node on the left, create a new JMS Server. The name is free. c) Built two Queue for JMS Server established. JNDI names are :: JMS / Calculate and JMS / Completed. d) Create a ConnectionFacotry. JNDI Name: JMS / Conn_Factory 3. Configure MDB.

转载请注明原文地址:https://www.9cbs.com/read-83783.html

New Post(0)