赞
踩
RabbitMQ消息中间连两端链接上消息生产者,消息消费者
但是在整合SpringBoot,且版本在
<spring-boot.version>2.6.13</spring-boot.version>
消息消费者,启动报错
消息发送者消息发送报错,
com.rabbitmq.client.ShutdownSignalException: channel error protocol method:
追踪问题根源是,队列,交换机,绑定这些都不存在,所以出现了问题,
解决办法很见简单
1.自己手动到RabbitMQ里面创建相关的交换机,队列,绑定关系
2.代码端解决
消息消费者
使用如下
- package com.example.rabbitmqb.config;
-
-
- import org.springframework.amqp.core.Message;
- import org.springframework.amqp.rabbit.annotation.Queue;
- import org.springframework.amqp.rabbit.annotation.RabbitListener;
- import org.springframework.stereotype.Component;
-
- import java.io.UnsupportedEncodingException;
-
-
- @Component
- public class RabbitMQConfig {
-
- @RabbitListener(queuesToDeclare = {@Queue("boot_queue")})
- public void ListenerQueues(Message message) throws UnsupportedEncodingException {
- System.out.println(new String(message.getBody(), "UTF-8"));
- }
-
- }
消息生产端配置类
- package com.example.rabbitmqa.config;
-
- import org.springframework.amqp.core.*;
- import org.springframework.beans.factory.annotation.Qualifier;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.amqp.rabbit.connection.ConnectionFactory;
- import org.springframework.amqp.rabbit.core.RabbitAdmin;
- import org.springframework.context.annotation.Bean;
-
- @Configuration
- public class RabbitMQConfig2 {
-
- // @Bean
- // RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
- // return new RabbitAdmin(connectionFactory);
- // }
-
- public static final String EXCHANGE_NAME = "boot_topic_exchange";
- public static final String QUEUE_NAME = "boot_queue";
-
- //1.交换机
- @Bean("bootExchange")
- public TopicExchange bootExchange(RabbitAdmin rabbitAdmin) {
-
- TopicExchange exchange = new TopicExchange(EXCHANGE_NAME);
- rabbitAdmin.declareExchange(exchange);
- return exchange;
- }
-
- //2.Queue 队列
- @Bean("bootQueue")
- public Queue bootQueue(RabbitAdmin rabbitAdmin) {
- Queue queue = new Queue(QUEUE_NAME, true);
- rabbitAdmin.declareQueue(queue);
- return queue;
- }
-
- //3. 队列和交互机绑定关系 Binding
- /*
- 1. 知道哪个队列
- 2. 知道哪个交换机
- 3. routing key
- */
- @Bean
- public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue,
- @Qualifier("bootExchange") Exchange exchange,
- RabbitAdmin rabbitAdmin) {
- Binding binding = BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
- rabbitAdmin.declareBinding(binding);
- return binding;
- }
-
-
- //创建初始化RabbitAdmin对象
- @Bean
- public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
- RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
- // 只有设置为 true,spring 才会加载 RabbitAdmin 这个类
- rabbitAdmin.setAutoStartup(true);
- return rabbitAdmin;
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。