RabbitMQ系列之springboot整合rabbitmq

本文介绍了如何使用SpringBoot简化RabbitMQ的配置和操作,包括引入依赖、配置MQ连接参数、注册交换机和队列、创建生产者和消费者,并提供了测试示例。通过SpringBoot的starter-amqp,可以实现快速便捷的消息队列操作。
摘要由CSDN通过智能技术生成

前面章节学习都是基于spring,配置麻烦,现在生产中也没人那么使用,下面讲解基于springboot来操作MQ

代码地址:https://gitee.com/webprogram/springboot_rabbit

SpringBoot整合RabbitMQ

引入依赖

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

配置

spring:
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: admin
    password: admin
    virtual-host: my_vhost
    publisher-confirm-type: correlated #开启交换机应答
    publisher-returns: true #开启队列应答
    template:
      mandatory: true #开启强制消息投递
    listener:
      simple:
        acknowledge-mode: manual #手动应答
        concurrency: 1 #当前监听容器数
        max-concurrency: 1 #当前监听最大容器数
        retry:
          enabled: true #开启重试

注册交换机、队列

@Configuration
public class RabbitConfig {
    // 定义交换机,类型TOPIC
    @Bean
    public Exchange topicExchange() {
        return ExchangeBuilder.topicExchange("topic_exchange").build();
    }
	
    // 定义队列,nonDurable不支持持久化的
    @Bean
    public Queue topicQueue() {
        return QueueBuilder.nonDurable("topic_queue").build();
    }
	
    // 绑定交换机和队列,实际生产为了灵活采用rabbit控制台进行操作绑定
    @Bean
    public Binding topicBinding(@Qualifier("topicQueue") Queue topicQueue, @Qualifier("topicExchange") Exchange topicExchange) {
        return BindingBuilder.bind(topicQueue).to(topicExchange).with("topic.#").noargs();
    }
}

生产者

@Autowired
private RabbitTemplate rabbitTemplate; 
public String sendMessage(String message) {
        Message messageBody = new Message(message.getBytes());
        rabbitTemplate.convertAndSend("topic_exchange", routing, messageBody);
        return "发送成功";
    }

消费者

@Component
public class RabbitListenerComponent {
    // 绑定要监听的队列
    @RabbitListener(queues = "topic_queue")
    public void printMessage(Message message) throws IOException {  
      System.out.println(new String(message.getBody())); 
}

测试

调用生产者方法发送消息,消费者会自动监听队列,如果有消息入队,则控制台成功打印出消息

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值