美文网首页
SpringBoot 整合 RabbitMQ 步骤

SpringBoot 整合 RabbitMQ 步骤

作者: bin丶 | 来源:发表于2020-11-24 21:17 被阅读0次

一、安装软件

  • 安装erlang,地址:https://www.erlang.org/
  • 修改环境变量,添加ERLANG_HOME,添加path 【与java一致】
  • 安装rabbitMQ,地址:https://www.rabbitmq.com/ 【注意版本支持问题】
  • 启动可视化管理界面 rabbitmq-plugins enable rabbitmq_management 【需要在sbin目录下使用或者配置了path】
  • 安装并启动成功后访问 localhost:15672,默认用户名和密码是guest


    管理界面

二、pom.xml 配置

  • 只需要在springboot初始配置下添加如下依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency> 

三、yml配置 - 生产者和消费者一致

# 可以指定自己设置的虚拟路径和用户
spring:
  rabbitmq:
    host: localhost
    port: 5672
    virtual-host: /  
    username: guest
    password: guest

四、生产者(producer)配置

  • 声明交换机、队列、路由key及绑定
@Configuration
public class RabbitMQConfig {

    // 交换机名称
    public static final String EXCHANGE_NAME = "spingboot_topic_exchange";
    // 队列名称
    public static final String QUEUE_NAME = "topic_queue";

    // 声明交换机
    @Bean("topicExchange")
    public Exchange topicExchange(){

        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    }

    // 声明队列
    @Bean("topicQueue")
    public Queue topicQueue(){

        return QueueBuilder.durable(QUEUE_NAME).build();
    }

    // 绑定
    @Bean
    public Binding topicBinding(@Qualifier("topicQueue") Queue queue, @Qualifier("topicExchange") Exchange exchange){
        // 绑定队列与交换机,并设置路由key = topic.#
        return BindingBuilder.bind(queue).to(exchange).with("topic.#").noargs();
    }
}

五、消费者(consumer)代码

@Component
public class Mylistener {
    // 队列名称与生产者定义的要一致
    @RabbitListener(queues = "topic_queue")
    public void myListener1(String message) {
        System.out.println("消费者接收到消息: " + message);
    }
}

六、测试(producer)代码

  • 先跑一遍测试,再启动consumer的服务
@SpringBootTest
class ProducerApplicationTests {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    void contextLoads() {
        //  将消息按指定路由key发送到交换机
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,
                "topic.insert", "test msg1");
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,
                "topic.update", "test msg2");
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,
                "topic.delete", "test msg3");
    }

}

相关文章

网友评论

      本文标题:SpringBoot 整合 RabbitMQ 步骤

      本文链接:https://www.haomeiwen.com/subject/zmuwiktx.html