SpringBoot集成RabbitMQ(生产者)

SpringBoot集成RabbitMQ(生产者)的步骤如下:

  1. 创建SpringBoot工程
  2. Maven添加 spring-boot-starter-amqp
  3. 编写application.properties配置RabbitMQ的信息
  4. 添加RabbitListener监听

前面三步省略。

1. 添加RabbitListener

消费者其实是起到一个监听的作用,可以通过一个@RabbitListener 注解配置监听作用

package com.lqk.comsumer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author lqk
 * @Date 2021/6/14
 * @Description
 */
@Slf4j
@Component
public class ConsumerConfig {

    @RabbitListener(queues = {"topic_queue_name"})
    public void listener(Message message){
        log.info(message.toString());
    }
}

每次有新消息来到的时候,都会输出message的信息。

Message的关键的信息如下:

// 此条消息的属性
private final MessageProperties messageProperties;
// 消息体
private final byte[] body;

public String toString() {
    StringBuilder buffer = new StringBuilder();
    buffer.append("(");
    buffer.append("Body:'").append(this.getBodyContentAsString()).append("'");
    buffer.append(" ").append(this.messageProperties.toString());
    buffer.append(")");
    return buffer.toString();
}

2. 结果

输出信息如下:

2021-06-14 17:40:00.467  INFO 16268 --- [ntContainer#0-1] com.lqk.comsumer.ConsumerConfig          : (Body:'hi~ha' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=true, receivedExchange=exchange_name, receivedRoutingKey=test.hello, deliveryTag=1, consumerTag=amq.ctag-XrEToEgb1VKD0u_dmkmG_w, consumerQueue=topic_queue_name])
2021-06-14 17:40:00.467  INFO 16268 --- [ntContainer#0-1] com.lqk.comsumer.ConsumerConfig          : (Body:'hi~ha' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=exchange_name, receivedRoutingKey=test.hello, deliveryTag=2, consumerTag=amq.ctag-XrEToEgb1VKD0u_dmkmG_w, consumerQueue=topic_queue_name])

你可能感兴趣的:(RabbitMQ,spring,boot,java-rabbitmq,rabbitmq)