配置类
package com.zhao.sian.config;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.ExchangeBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
@Value("${amqp-binding.queue-name}")
private String queueName;
@Value("${amqp-binding.exchange-name}")
private String exchangeName;
@Value("${amqp-binding.routing-key}")
private String routingKey;
@Bean
public TopicExchange topicExchange() {
return (TopicExchange) ExchangeBuilder.topicExchange(exchangeName).durable(true).build();
}
@Bean
public Queue queue() {
return new Queue(queueName);
}
@Bean
public Binding alterUserBinding(TopicExchange topicExchange, Queue queue) {
return BindingBuilder.bind(queue).to(topicExchange).with(routingKey);
}
//---------------------------- batch 批量
@Bean("batchQueueRabbitListenerContainerFactory")
public SimpleRabbitListenerContainerFactory batchQueueRabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
//设置批量
factory.setBatchListener(true);
factory.setConsumerBatchEnabled(true);
factory.setBatchSize(10000);
factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
return factory;
}
}
批量消费的类
package com.zhao.sian.listener;
import java.io.IOException;
import java.util.List;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
/**
*
* @author Yongqian.Zhao
*
*/
@Slf4j
@Component
public class BatchQueueListener implements ChannelAwareMessageListener {
// 批量接收处理
@RabbitListener(queues = "acedemy.learning-test" , containerFactory = "batchQueueRabbitListenerContainerFactory")
@Override
public void onMessageBatch(List<Message> messages, Channel channel) {
try {
log.info("batch.queue.consumer 收到{}条message", messages.size());
if (messages.size() > 0) {
log.info("第一条数据是: {}", new String(messages.get(0).getBody()));
}
channel.basicAck(messages.size(), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onMessage(Message message, Channel channel) throws Exception {
// TODO Auto-generated method stub
}
}