消费消息的两种方式:
1.SimpleMessageListenerContainer
@Bean(value = "myRabbitListenerContainer")
public SimpleMessageListenerContainer simpleMessageListenerContainer(ConnectionFactory connectionFactory) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
//设置并发消费者的数量(MessageConsumer)
//container.setConcurrentConsumers(5);
//container.setMaxConcurrentConsumers(10);
//设置消费的队列 , 队列可以是多个(参数是String的数组)
container.setQueueNames("Direct-Queue", "TTL-Failure-Queue");
/**
* SimpleMessageListenerContainer的生命周期随着spring容器的启动而启动,关闭而关闭
* 这里设置spring容器初始化的时候设置SimpleMessageListenerContainer不启动
*/
//container.setAutoStartup(false);
//设置消费者的consumerTag_tag
ConsumerTagStrategy consumerTagStrategy = new ConsumerTagStrategy() {
@Override
public String createConsumerTag(String s) {
return "newTag-" + s + "-" + (++count);
}
};
container.setConsumerTagStrategy(consumerTagStrategy);
//设置消费者的Arguments
Map<String, Object> args = new HashMap<String, Object>();
args.put("module","订单模块");
args.put("fun","发送消息");
container.setConsumerArguments(args);
container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
container.setMessageListener(new ChannelAwareMessageListener() {
@Override
//得到channel,可以对消息进行操作
public void onMessage(Message message, Channel channel) throws Exception {
System.out.println("消费方式一: 接收到的消息 message : " + message);
channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
//channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
}
});
//后置处理器,接收到的消息都添加了Header请求头
container.setAfterReceivePostProcessors(new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) throws AmqpException {
message.getMessageProperties().getHeaders().put("desc",10);
return message;
}
});
return container;
}
2.通过@RabbitListener和@RabbitHandler
@Component
public class RabbitMQReceive {
//@RabbitListener(containerFactory = "myRabbitListenerContainerFactory", queues = "Direct-Queue", group = "group", id = "id")
//监听器监听指定的Queue
public void reveive(String str) {
System.out.println("Direct Receive: " + str);
}
@RabbitListener(queues = "Topic-Queue-3", exclusive = true)
//监听器监听指定的Queue
public void topicReceive(String str) {
System.out.println("Topic Receive: " + str);
}
/**
* 在未创建队列和exchange的时候可以通过bindings来新建
*
* @param order
* @param headers
* @param channel
* @throws Exception
*/
@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "order-queue", durable = "true"),
exchange = @Exchange(value = "order-exchange", durable = "true", type = "topic"),
key = "order.#"))
@RabbitHandler
public void onOrderMessage(@Payload String order, @Headers Map<String, Object> headers, Channel channel) throws Exception {
System.out.println("--------------收到消息,开始消费------------");
System.out.println("订单ID是:" + order);
Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
// ACK
channel.basicAck(deliveryTag, false);
}
}