Battle JMS (transfer) Select from Blade

xiaoxiao2021-03-06  35

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 before using the system design, let's go back to familiarize some of JMS. 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 consumption forms, the JMS has two sets of parallel API, 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. The following is the basic model of the JMS application: (This map is from Sun's Online Document JMS Tutorial listing several up to several longest API: l QueueConnectionFactory and TopicConnectionFactory Connection Factory for generating QueueConnection and TopicConnection, based on this model QueueConnection and TopicConnection connection objects are used to create a connection to JMS and generate session instances l Queuesession and TopicSession session objects used to create messages, messages producers and messages (explaining the producer of the message: It does not represent generation messages The objects of the instance refers to the object to be sent to the JMS. 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. The design system is too simple, and it is simply explained the software's operating environment and execution process. This MIS system is the B / S mode. Web Browser will send a message after completing the addition of the execution task (saved to the database). Give the calculation program, this calculation process is implemented into MDB. After the calculation, the message will be sent to the web browser that generates the task. Don't think that I really can do this, active put the message to the Web Browser author, there is no The power, here uses a way to use an applet: The applet itself is also a running thread and a servlet that receives the message every other period of time. If there is a message, it is prompted if there is a message. 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. Hand implementation 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.

Availability of resources: public void init () throws ServletException {try {InputStream in = this.getClass () getClass () getClassLoader () getResourceAsStream ( "jndi.properties"); Properties p = new Properties (); p.load... (in); ctx = new InitialContext (p);} catch (Exception ex) {ex.printStackTrace ();} try {connectionFactory = (QueueConnectionFactory) ctx.lookup (connectionFactoryName); queue = (Queue) ctx.lookup (queueName ); connection = (javax.jms.QueueConnection) ((QueueConnectionFactory) connectionFactory) createQueueConnection (); queueSession = ((javax.jms.QueueConnection).. connection) createQueueSession (false, Session.AUTO_ACKNOWLEDGE); queueSender = queueSession.createSender ( Queue);} catch (exception ex) {ex.printStackTrace ();}} Send message: public void doget (httpservletRequest Request, httpservletResponse response) throws servletexception, oExceptio n {String taskid = request.getParameter ( "taskid"); try {String completedmsg = "Tasks" taskid "execution is complete"; ObjectMessage om = queueSession.createObjectMessage (new CalculateCompleted (userid, taskid, completedmsg)); 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 method 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.

Here, in addition to specifying the Queue of the MDB listener, because the MDB needs to send a successful message to another Queue, you also need to add JMS / Conn_Factory configured in WebLog as a resource to the MDB's Resource-Ref, put JMS / Completed as Environmental resources are added to the MDB's resource-env-resource. 4. Deployment. Establish an EAR with JBuilder and deploy it very simple. If you want to test only a simple client application, you can forward the MDB onMessage method to forward the message. Summary The author's beginner JMS can only talk about JMS's most basic application. JMS is a very powerful API, not only to implement asynchronous communication in an application, but also often used to deliver data between different applications, and JMS also supports distributed transactions, reaching the requirements of corporate applications, the author I believe that as learning and application continues to deepen, JMS is more powerful. Author Blog:

http://blog.9cbs.net/blade_sea/

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

New Post(0)