项目中RabbitMQ的基本使用


简单介绍在项目中基本使用RabbitMQ,从RabbitMQ的接收和发送信息来举例

RabbitMQ的引入

项目引入spring cloud Bus的依赖,完成项目中服务与RabbitMQ的连接

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

RabbitMQ的信息发送方

使用注入的方式使用AmqpTemplate

@Autowired
private AmqpTemplate amqpTemplate;

AmqpTemplate含有许多种发送消息的方式。

上边图中的方法为发送RabbitMQ的方式提供了多样化。我这边介绍最简单的方式

/**
    * @Description: 发送MQ消息
    * "myQueue" -> 消息发送的目标
    * "message" -> 消息
    */
amqpTemplate.convertAndSend("myQueue", message);

RabbitMQ的信息接收方

消息接收的三种方式。代码如下

// 1. 非自动创建Queue,如果启动前没有创建Queue,会抛出 Failed to declare [myQueue]
@RabbitListener(queues = "myQueue")
// 2. 自动创建队列Queue
@RabbitListener(queuesToDeclare = @Queue("myQueue"))
// 3. Exchange和Queue绑定
@RabbitListener(bindings = @QueueBinding(
            value = @Queue("myQueue"),
            exchange = @Exchange("myExchange")
    ))

接收RabbitMQ的消息在SpringBoot项目中使用的是@RabbitListener。这块的配置同样也是需要自己配置的

想要了解@RabbitListener注解中各个方法的定义请看RabbitListener


 上一篇
项目打包成镜像 项目打包成镜像
项目打包成镜像并推送至阿里云的镜像仓库 项目打包成jar包 $ mvn clean package -Dmaven.test.skip=true 打包成功之后,首先还有比较重要的一步,编写Dockerfile ## 运行在openjdk
2020-08-28
下一篇 
Spring Cloud Bus 配置文件实现自动更新 Spring Cloud Bus 配置文件实现自动更新
上篇文章中描述了使用git仓库保存项目的配置文件,其他项目通过关联配置中心,实现统一配置中心。 在生产环境中,很少通过重启项目来改变项目的配置文件的。本篇将对Spring Cloud Bus如何实现保证项目运行的过程下,改变远程git仓库
2020-08-18
  目录