RabbitMQ学习(三)-springboot整合RabbitMQ


title: RabbitMQ学习(三)-springboot整合RabbitMQ
date: 2021-1-11
tags:

  • 微服务
  • RabbitMQ学习(三)-springboot整合RabbitMQ
  • RabbitMQ
  • spring
  • springboot
    categories:
  • 微服务
  • RabbitMQ
  • RabbitMQ学习(三)-springboot整合RabbitMQ

一、环境搭建

1.1 创建一个简单的springboot项目

创建一个名为springboot-rabbitmq的springboot项目。

1.2 导入相关依赖

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

1.3 编写配置文件

spring:
  rabbitmq:
    host: 192.168.31.138
    port: 5672
    username: test
    password: test
    virtual-host: /test

二、具体实现

2.1 编写RabbitMQ的配置类

编写一个名为RabbitMQConfig的配置类,进行exchange和queue的声明和绑定。

@Configuration
public class RabbitMQConfig {

    //1.创建exchange - topic
    @Bean
    public TopicExchange topicExchange(){
        return new TopicExchange("springboot-topic-exchange",true,false);
    }

    //2.创建queue
    @Bean
    public Queue queue(){
        return new Queue("springboot-queue",true,false,false,null);
    }

    //3.将exchange和queue绑定在一起
    @Bean
    public Binding binding(TopicExchange topicExchange,Queue queue){
        return BindingBuilder.bind(queue).to(topicExchange).with("*.red.*");

    }

}

2.1 发布消息

通过rabbitTemplate的convertAndSend()方法进行消息的发布,他需要三个参数:

  1. 参数1 指定交换机exchange
  2. 参数2 指定routingKey
  3. 参数3 指定具体要发布的消息
@SpringBootTest
class SpringbootRabbitmqApplicationTests {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    void publish() {
        rabbitTemplate.convertAndSend("springboot-topic-exchange","slow.red.dog","慢红狗");
    }

}

2.2 监听消息

通过@RabbitListener( )的queues属性指定要监听的队列。

@Component
public class Consumer {
    @RabbitListener(queues = "springboot-queue")
    public void getMessage(Object message){
        System.out.println("接收到的消息:"+message);
    }
}

三、手动ACK

3.1 修改配置文件

spring:
  rabbitmq:
    host: 192.168.31.138
    port: 5672
    username: test
    password: test
    virtual-host: /test
    listener:
      direct:
        acknowledge-mode: manual

3.2 修改监听者

在消费消息的地方进行通过basicAck()方法进行手动ACK

@Component
public class Consumer {
    @RabbitListener(queues = "springboot-queue")
    public void getMessage(String msg, Channel channel, Message message) throws IOException {
        System.out.println("接收到的消息:"+msg);
        //手动Ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值