Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of sending and receiving messages by combining ActiveMQ with Spring

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces in detail the method of "ActiveMQ combined with Spring to send and receive messages". The content is detailed, the steps are clear, and the details are handled properly. I hope that this "ActiveMQ combined with Spring method of sending and receiving messages" can help you solve your doubts.

ActiveMQ combined with Spring to send and receive messages

Using ActiveMQ directly requires a lot of rewriting of code and is not easy to manage. Spring provides an easier way-Spring JMS, through which you can use ActiveMQ more easily.

Maven dependence

The dependencies for using ActiveMQ with Spring are as follows:

Org.springframework

Spring-jms

${spring.version}

Org.apache.xbean

Xbean-spring

3.16

Org.apache.activemq

Activemq-core

5.7.0

Org.apache.activemq

Activemq-pool

5.7.0

ActiveMQ.xml file

Configure connectionFactory

ConnectionFactory is used by Spring to create links to JMS servers, and Spring provides a variety of connectionFactory.

Configure Queue

Configure Topic

Configure JMS message template-jmsTemplate

Finally, introduce the configured ActiveMQ.xml into applicationContext.xml

one

The above is related to the configuration file, and the following is the specific business code.

Message producer service

@ Service

Public class ProducerService {

@ Autowired

Private JmsTemplate jmsTemplate

/ / use the default destination

Public void sendMessageDefault (final String msg) {

Destination destination = jmsTemplate.getDefaultDestination ()

System.out.println ("to queue:" + destination + "send a message successfully")

JmsTemplate.send (new MessageCreator () {

Public Message createMessage (Session session) throws JMSException {

Return session.createTextMessage (msg)

}

});

}

/ / destination can be specified

Public void sendMessage (Destination destination,final String msg) {

JmsTemplate.send (destination, new MessageCreator () {

Public Message createMessage (Session session) throws JMSException {

Return session.createTextMessage (msg)

}

});

}

}

Message consumer service

@ Service

Public class ConsumerService {

@ Autowired

Private JmsTemplate jmsTemplate

/ / receive messages from the specified Destination

Public TextMessage recive (Destination destination) {

TextMessage message = (TextMessage) jmsTemplate.receive (destination)

Try {

System.out.println ("from queue" + destination.toString () + "received message" + message.getText ())

} catch (JMSException e) {

E.printStackTrace ()

}

Return message

}

/ / receive messages from the default Destination

Public void reciveDefault () {

Destination destination = jmsTemplate.getDefaultDestination ()

JmsTemplate.setReceiveTimeout (5000)

While (true) {

TextMessage message = (TextMessage) jmsTemplate.receive (destination)

Try {

/ / here is still the same consumer

System.out.println (Consumer from destination + destination.toString () + received message + message.getText ())

} catch (JMSException e) {

E.printStackTrace ()

}

}

}

}

Producer

Get the ApplicationContext run directly in the main method to facilitate testing.

@ Component

Public class MsgProducer {

@ Autowired

Private ProducerService producerService

Public void send () {

System.out.println ("producer starts sending message:")

For (int I = 1; I < 11; iTunes +) {

String msg = "message from the producer"

ProducerService.sendMessageDefault (msg + "-" + I)

}

}

Public static void main (String [] args) {

ApplicationContext context = new ClassPathXmlApplicationContext ("classpath:/applicationContext.xml")

MsgProducer msgProducer = context.getBean (MsgProducer.class)

MsgProducer.send ()

}

}

Consumer

@ Component

Public class MsgConsumer {

@ Autowired

Private ConsumerService consumerService

Public void recive () {

System.out.println ("Consumer 1 starts to receive messages:")

ConsumerService.reciveDefault ()

}

Public static void main (String [] args) {

ApplicationContext context = new ClassPathXmlApplicationContext ("classpath:/applicationContext.xml")

MsgConsumer msgConsumer = context.getBean (MsgConsumer.class)

MsgConsumer.recive ()

}

}

Then you can start the project. It is also tested in two ways.

The first way-- point to point (Queue)

Synchronized mode

First start the producer to send 10 messages, and then start the consumer, you can see that the console has successfully received 10 messages.

The way of asynchronous monitoring

The effect of receiving messages asynchronously can be achieved through a listener, rather than using while () polling synchronization as above.

Asynchronous monitoring is generally used in the project, a message is sent in A service, and B service can use message listener to listen, and when the message is received, the corresponding operation is carried out.

Message listeners (3)

By inheriting the MessageListener interface in JMS and implementing the onMessage () method, you can customize the listener. This is the most basic listener. (custom functions can be implemented according to the business)

In addition, spring also provides us with other types of message listeners, such as SessionAwareMessageListener, which can not only receive messages, but also send a message to notify the other party that they have received the message. (another is MessageListenerAdapter)

A simple custom listener is as follows: print a message after receiving it

Public class QueueMessageListener implements MessageListener {

Public void onMessage (Message message) {

/ / if there is any news

TextMessage tmessage = (TextMessage) message

Try {

If (tmessage! = null) {

System.out.println ("listeners listen for messages:" + tmessage.getText ())

}

} catch (JMSException e) {

E.printStackTrace ()

}

}

}

Introduce message listeners in ActiveMQ.xml:

As you can see, after using the message listener, each message sent is immediately monitored:

The second way-publish / subscribe (Topic)

Synchronized mode

It is similar to peer-to-peer synchronization, except that every consumer can receive all the messages sent by the producer.

The way of asynchronous monitoring

Start two listeners (two consumers) to listen for messages asynchronously. See if each can receive a message from the producer.

As you can see, each listener received 10 messages from the producer.

After reading this, the article "the method of ActiveMQ combined with Spring to send and receive messages" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, you are welcome to follow the industry information channel.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report