Springboot integrates Rabbitmq production and consumption instances

After sorting out the articles on rabbitmq architecture principles and deployment, there is still a lack of a complete integrated use process in terms of use. Just in time for the Mid-Autumn Festival holiday, build a springboot project example, improve springboot integration rabbitmq to realize the process of message producers sending messages and consumers consuming messages, and record them here for continuous in-depth study and reference for latecomers. Inevitably omissions, I hope readers will correct me, I would be very grateful; at the same time, I wish all readers a happy Mid-Autumn Festival and a happy family!

1. Introduce dependencies

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2. Producer

2.1 Configuration file

spring.rabbitmq.addresses=192.168.65.155:5672,192.168.65.156:5672,192.168.65.157:5672
spring.rabbitmq.username=test_user
spring.rabbitmq.password=test_pwd
spring.rabbitmq.virtual-host=/
spring.rabbitmq.connection-timeout=15000
spring.rabbitmq.publisher-confirm-type=correlated
spring.rabbitmq.publisher-returns=true

2.2 Switch and queue binding

@Configuration
public class RabbitMqConfig {

    //交换机名称
    public static final String ITEM_TOPIC_EXCHANGE = "item_topic_exchange";

    //队列名称
    public static final String ITEM_QUEUE = "item_queue";

    //声明交换机
    @Bean("itemTopicExchange")
    public Exchange topicExchange(){
        return ExchangeBuilder.topicExchange(ITEM_TOPIC_EXCHANGE).durable(true).build();
    }

    //声明队列
    @Bean("itemQueue")
    public Queue itemQueue(){
        return QueueBuilder.durable(ITEM_QUEUE).build();
    }

    //绑定队列和交换机
    @Bean
    public Binding itemQueueExchage(@Qualifier("itemQueue")Queue itemQueue,
                                    @Qualifier("itemTopicExchange") Exchange itemTopicExchange){
        return BindingBuilder.bind(itemQueue).to(itemTopicExchange).with("item.#").noargs();
    }

}

2.3 Producer sends message

public interface QueueMessageService extends RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {
    /**
     * 发送消息到rabbitmq消息队列
     * @param message 消息内容
     * @param exchange 交换配置
     * @param queueRoutingKey routingKey的队列
     * 
     */
    void send(Object message, String exchange, String queueRoutingKey);
}

@Service
public class QueueMessageServiceImpl implements QueueMessageService {

    private static final Logger logger = LoggerFactory.getLogger(QueueMessageServiceImpl.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    @Override
    public void send(Object message, String exchange, String queueRoutingKey) {
        rabbitTemplate.convertAndSend(exchange,queueRoutingKey,message);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
    	// 消息由producer发送至exchange返回结果,发送成功时 b为true,失败时为false
        logger.info("==========confirm==============:{},{},{}",correlationData,b,s);
    }

    @Override
    public void returnedMessage(Message message, int i, String s, String s1, String s2) {
    	// 消息由exchange传递进入queue过程中,失败时触发
        logger.info("===========returnedMessage=============:{},{},{},{},{}",message,i,s,s1,s2);
    }
}

2.4 Producer ConfirmCallBack and ReturnCallBack

insert image description here
The confirmation from the producer to the route listens to the ConfirmCallback;
if the message is not successfully sent from the route to the queue, the ReturnCallBack callback will be used to return the entire details of the message.

3. Consumers

3.1 Configuration file

spring.rabbitmq.addresses=192.168.65.155:5672,192.168.65.156:5672,192.168.65.157:5672
spring.rabbitmq.username=test_user
spring.rabbitmq.password=test_pwd
spring.rabbitmq.virtual-host=/
spring.rabbitmq.connection-timeout=15000

3.2 Consuming news

@Configuration
public class RabbitmqConfig {
    //队列名称
    public static final String ITEM_QUEUE = "item_queue";
}

@Component
public class ConsumerService {

    private static final Logger logger = LoggerFactory.getLogger(ConsumerService.class);

    @RabbitListener(queues = RabbitmqConfig.ITEM_QUEUE)
    @RabbitHandler
    public void consumeMessage(Message message){
        logger.info("收到的消息:{}",message);
    }

}

4. References

[1] https://blog.csdn.net/liuhenghui5201/article/details/107299321
[2] https://blog.csdn.net/xibei19921101/article/details/108140830
[3] https://www.jianshu.com/p/3411feeb115f

Guess you like

Origin blog.csdn.net/shy871/article/details/120381707