6. Using RabbitMQ in traditional Spring
6. Using RabbitMQ in traditional Spring
Table of contents
[RabbitMQ column directory (click to enter...)](https://blog.csdn.net/qq_45305209/article/details/135846863)
Using RabbitMQ in traditional Spring
- Table of contents
- Using RabbitMQ in traditional Spring
-
- 1. Import dependencies
- 2.rabbitmq-config.properties configuration file
- 3.applicationContext-rabbitmq.xml
- 4. Sending message interface (Producer, producer)
- 5. Send message interface implementation class
- 6. Receive messages asynchronously (Consumer)
- 7.Testing
Using RabbitMQ in traditional Spring
1. Import dependencies
<!-- RabbitMQ Intermediate Messaging -->
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-amqp</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.7.3</version>
</dependency>
<!-- depends on the Spring context and so on, so if you use RabbitMQ, you should also use the corresponding version of Spring. -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
2.rabbitmq-config.properties configuration file
# host address
mq.host=127.0.0.1
#Virtual host username
mq.username=test
#Password
mq.password=123456
#port number
mq.port=5672
#virtualhostname
mq.virtualHost=/rabbit
#queue name
mq.queue=rabbitmq_test
#exchange name
mq.exchange=rabbitmq_exchange
3.applicationContext-rabbitmq.xml
<! -- Connection Configuration -->
<rabbit:connection-factory id="connectionFactory" host="${mq.host}" username="${mq.username}" password="${mq.password}" port="${mq.port }" virtual-host="${mq.virtualHost}" />
<rabbit:admin connection-factory="connectionFactory" />
<! -- Message object json conversion class -->
<bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter" />
<! -- spring AmqpTemplate declaration -->
<rabbit:template exchange="amqpExchange" id="amqpTemplate" connection-factory="connectionFactory" message-converter=" jsonMessageConverter" />
<! -- Declare a message queue Queue -->
<rabbit:queue id="queue-name" name="${mq.queue}" durable="true" auto-delete="false" exclusive="false" />
<! -- Switch Definitions -->
<! -- rabbit:direct-exchange defines the exchange mode as direct, meaning that a message is forwarded only if it exactly matches a specific routing key -->
<! -- durable Whether durable or not.
exclusive A private queue available only to the creator, automatically deleted upon disconnection.
auto_delete Whether to automatically delete the queue when all consuming clients are disconnected.
-->
<rabbit:direct-exchange id="mq-exchange" name="${mq.exchange}" durable="true" auto-delete="false">
<! -- Set the key that the message queue matches -->
<rabbit:bindings
<rabbit:binding queue="queue_name" key="test_queue_key" />
</rabbit:bindings
</rabbit:direct-exchange
<! -- Listener Configuration -->
<rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto">
<! --
queues: queues to listen to, separated by commas (,) if more than one.
ref: listener
-->
<rabbit:listener queues="queue-name" ref="queueListenter" />
</rabbit:listener-container
<bean id="queueListenter" class="com.my.mq.QueueListenter"/>
4. Sending message interface (Producer, producer)
// Queue Producer
public interface MQProducer {
// Send a message to the specified queue
public void sendDataToQueue(String queueKey, Object object); }
}
5. Send message interface implementation class
@Service
public class MQProducerImpl implements MQProducer {
private final static Logger logger = LoggerFactory.getLogger(MQProducerImpl.class);
@Autowired
private AmqpTemplate amqpTemplate;
@Override
public void sendDataToQueue(String queueKey, Object object) {
try {
amqpTemplate.convertAndSend(queueKey, object);
} catch (Exception e) {
logger.error(e.toString());
}
}
}
convertAndSend: Convert Java objects into messages and send them to the exchange that matches the Key. Since JSON conversion is configured, here is the form of converting Java objects into JSON strings.
AmqpTemplate
Spring AMQP provides an operation template class AmqpTemplate for sending and receiving messages. AmqpTemplate defines some basic operational functions including sending and receiving messages. RabbitTemplate is an implementation of AmqpTemplate.
RabbitTemplate supports message confirmation and return. In order to return messages, RabbitTemplate needs to set the mandatory attribute to true, and the publisherReturns attribute of CachingConnectionFactory also needs to be set to true. The returned message will be sent to the client according to its registered RabbitTemplate.ReturnCallback setReturnCallback callback. A RabbitTemplate can only support one ReturnCallback.
In order to confirm the Confirms message, the publisherConfirms property of CachingConnectionFactory also needs to be set to true, and the confirmed message will be sent to the client according to its registered RabbitTemplate.ConfirmCallback setConfirmCallback callback. A RabbitTemplate can only support one ConfirmCallback
6. Receive messages asynchronously (Consumer)
@Component
public class QueueListenter implements MessageListener {
@Override
public void onMessage(Message msg) {
try {
System.out.print(msg.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
7.Testing
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/applicationContext-mq.xml" })
public class TestQueue {
final String queue_key = "test_queue_key";
@Autowired
MQProducer mqProducer;
@Test
public void send() {
HashMap<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("data", "hello,rabbmitmq!");
mqProducer.sendDataToQueue(queue_key, hashMap);
}
}
Run the test program: Run with JUnit, a message will be sent to test_queue, and the listener will print out the message after listening to the message.