Spring integrates RabbitMQ-03-SimpleMessageListenerContainer

SimpleMessageListenerContainer

  1. Simple message listening container. This class is very powerful. We can set many settings for it. For message configuration items, this class can satisfy all requirements;
  2. Listen to the queue (multiple pairs), start automatically, and declare automatically
  3. Set transaction properties, transaction manager and transaction properties. Transaction capacity (concurrent), whether to start transaction, rollback message, etc
  4. Set the number of consumers, maximum and minimum quantity, mass consumption, etc
  5. Set message confirmation and automatic confirmation mode, whether to return to the queue, exception capture handler function
  6. Set consumer label generation policy, exclusive mode or not, consumer properties
  7. Set up specific listeners, message converters, etc

Be careful

SimpleMessageListenerContainer can be set dynamically, such as the number of its consumers and the mode of receiving messages. Many customized backend management consoles based on RabbitMQ are implemented according to this feature when they are dynamically set.

Code

package com.wyg.rabbitmq.springamqp;

import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.amqp.support.ConsumerTagStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.rabbitmq.client.Channel;

/**
 * RabbitAdmin
 * 
 * @author wyg0405@gmail.com
 * @date 2019-11-25 15:11
 * @since JDK1.8
 * @version V1.0
 */

@Configuration
public class RabbitConfig {

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
        cachingConnectionFactory.setAddresses("localhost:5672");
        cachingConnectionFactory.setUsername("guest");
        cachingConnectionFactory.setPassword("guest");
        cachingConnectionFactory.setVirtualHost("/");
        return cachingConnectionFactory;
    }
    
    /**
     * SimpleMessageListenerContainer injection
     * 
     * @param connectionFactory
     * @return
     * @throws @author
     *             wyg0405@gmail.com
     * @date 2019/11/25 17:16
     */
    @Bean
    public SimpleMessageListenerContainer simpleMessageListenerContainer(ConnectionFactory connectionFactory) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        // Listen to multiple queue s
        container.addQueueNames("test01", "test02", "test03");
        // Set current number of consumers
        container.setConcurrentConsumers(1);
        // Set the maximum number of consumers
        container.setMaxConcurrentConsumers(5);
        // Set do not return to queue
        container.setDefaultRequeueRejected(false);
        // Set up automatic sign in
        container.setAcknowledgeMode(AcknowledgeMode.AUTO);
        // Set the consumer tag strategy
        container.setConsumerTagStrategy(new ConsumerTagStrategy() {
            @Override
            public String createConsumerTag(String queue) {
                return queue + "_" + System.currentTimeMillis();
            }
        });

        // Set up monitoring
        container.setMessageListener(new ChannelAwareMessageListener() {
            @Override
            public void onMessage(Message message, Channel channel) throws Exception {
                // Message processing
                String msg = new String(message.getBody(), "UTF-8");
                System.out.println("---Consumer---Team name:" + message.getMessageProperties().getConsumerQueue() + "´╝îNews:" + msg
                    + ",deliveryTag: " + message.getMessageProperties().getDeliveryTag());
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);;
            }
        });

        return container;
    }

}

unit testing

package com.wyg.rabbitmq.springamqp;

import java.io.*;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.wyg.rabbitmq.springamqp.convert.Order;
import com.wyg.rabbitmq.springamqp.convert.User;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitConfigTest {
    @Autowired
    RabbitAdmin rabbitAdmin;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private SimpleMessageListenerContainer simpleMessageListenerContainer;

 
    @Test
    public void testSimpleMessageListenerContainerSendMsg() {
        // Send messages to the queues "test01", "test02", "test03", respectively, "test01", "test02",
        // "test03" is bound to springdemo.direct. routingKey is orderRoutingKey
        for (int i = 0; i < 3; i++) {
            rabbitTemplate.convertAndSend("springdemo.direct", "orderRoutingKey", ("The first" + i + "Bar message").getBytes());

        }
    }

}

Tags: Java RabbitMQ Junit JSON

Posted on Mon, 02 Dec 2019 01:39:27 -0500 by abie