Simple alternative implementation of MDB

xiaoxiao2021-03-06  15

The current project requires not to use EJB to complete the functionality that only EJB can implement, such as declarative transaction management. When making an asynchronous handling a business, I found that Spring did not provide MDB alternative implementation, it seems that I can only be implemented.

Because this is relatively simple, now put the relevant code here:

1. First define ConnectionFactory and a Destination in the Spring Profile

ConnectionFactory

Queue / MyQueue

2. Send Message

We can use the JMSTemplate provided by Spring to implement the functionality of the message:

JMSTemplate Template = New JMSTemplate (ConnectionFactory);

Template.send (Destination, New MessageCreat "

{

Public Message CreateMessage (Session Session) THROWS JMSEXCEPTION

{

Return session.createtextMessage (Message);

}

});

The ConnectionFactory and Destionation are specifically defined in Spring.

3. Message Consumer

We use a simple class to replace MDB. In order to achieve this, we need to consider the following questions:

· He needs to realize the MessageListener interface;

· He needs to listen to a Destination

· When the system starts, you can release this class.

We can solve these problems with the following method:

First define this class:

Public Class MessageConsuMerimpl Implements MessageListener

{

Public void init ()

{

}

Public void OnMessage (Message Message)

{

// process the message.

}

}

Then, when defining this bean in the Spring profile, define its init-method properties as follows:

Bind this class and a specific Destination in the init method, as follows:

Public void init () {

CONNECTION = (QueueConnection) ConnectionFactory.createConnection ();

Session session = connection.creatession (false,

Session.auto_acknowledge;

MessageConsumer consumer = session.createconsumer (destination);

Consumer.setMessagelistener (this);

Connection.start ();

}

Where MessageCroupumer is a class in the javax.jms package. Only one Queue is used as a message transmission of P2P, and the message of PUB-SUB is not tested.

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

New Post(0)