当前位置:   article > 正文

SpringAMQP的配置和使用_springamqp 发送消息

springamqp 发送消息

目录

利用SpringAMQP实现HelloWorld中的基础消息队列功能:

1.在父工程中引入spring-amqp的依赖

2.在publisher服务中利用RabbitTemplate发送消息到simple.queue这个队列

3.在consumer服务中编写消费逻辑,绑定simple.queue这个队列

模拟WorkQueue,实现一个队列绑定多个消费者:

1.在publisher服务中定义测试方法,每秒产生50条消息,发送到simple.queue

2.在consumer服务中定义两个消息监听者,都监听simple.queue队列,消费者1每秒处理50条消息,消费者2每秒处理10条消息

发布和订阅:

发布订阅-Fanout Exchange

利用SpringAMQP演示FanoutExchange的使用

1.在consumer服务中,利用代码声明队列、交换机,并将两者绑定

2.在consumer服务中,编写两个消费者方法,分别监听fanout.queue1和fanout.queue2

3.在publisher中编写测试方法,向itcast.fanout发送消息

发布订阅-DirectExchange

1.利用@RabbitListener声明Exchange、Queue、RoutingKey,在consumer服务中,编写两个消费者方法,分别监听direct.queue1和direct.queue2

2.在publisher中编写测试方法,向itcast. direct发送消息

发布订阅-TopicExchange

1.并利用@RabbitListener声明Exchange、Queue、RoutingKey,在consumer服务中,编写两个消费者方法,分别监听topic.queue1和topic.queue2

2.在publisher中编写测试方法,向itcast. topic发送消息

测试发送Object类型消息

​编辑 消息转换器


什么是AMQP?
·应用间消息通信的一种协议,与语言和平台无关。

SpringAMQP如何发送消息?
·引入amqp的starter依赖

·配置RabbitMQ地址
·利用RabbitTemplate的convertAndSend方法


SpringAMQP如何接收消息?

·引入amqp的starter依赖

·配置RabbitMQ地址
·定义类,添加@Component注解
·类中声明方法,添加@RabbitListener注解,方法参数就时消息

注意:消息一旦消费就会从队列删除,RabbitMQ没有消息回溯功能


Work模型的使用:
·多个消费者绑定到一个队列,同一条消息只会被一个
消费者处理
·通过设置prefetch来控制消费者预取的消息数量


交换机的作用是什么?

·接收publisher发送的消息
·将消息按照规则路由到与之绑定的队列

·不能缓存消息,路由失败,消息丢失
·FanoutExchange的会将消息路由到每个绑定的队列

声明队列、交换机、绑定关系的Bean是什么?

·Queue
·FanoutExchange

·Binding


描述下Direct交换机与Fanout交换机的差异?

·Fanout交换机将消息路由给每一个与之绑定的队列

·Direct交换机根据RoutingKey判断路由给哪个队列
·如果多个队列具有相同的RoutingKey,则与Fanout功能类似

基于@RabbitListener注解声明队列和交换机有哪些常见注解?

·@Queue
·@Exchange


SpringAMQP中消息的序列化和反序列化是怎么实现的?

·利用MessageConverter实现的,默认是JDK的序列化

·注意发送方与接收方必须使用相同的MessageConverter

SpringAMQP官网:https://spring.io/projects/spring-amqp

什么是AMQP: 

Advanced Message Queuing Protocol,是用于在应用程序或之间传递业务消息的开放标准。该协议与语言和平台无关,更符合微服务中独立性的要求。

什么是SpringAMQP:

Spring AMQP是基于AMQP协议定义的一套API规范,提供了模板来发送和接收消息。包含两部分,其中spring-amqp是基础抽象,spring-rabbit是底层的默认实现。

所有流程的文件相对位置:

利用SpringAMQP实现HelloWorld中的基础消息队列功能:

1.在父工程中引入spring-amqp的依赖

在mq-demo的pom文件导入:

<!--AMQP依赖,包含RabbitMQ-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>cn.itcast.demo</groupId>
  7. <artifactId>mq-demo</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <modules>
  10. <module>publisher</module>
  11. <module>consumer</module>
  12. </modules>
  13. <packaging>pom</packaging>
  14. <parent>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-parent</artifactId>
  17. <version>2.3.9.RELEASE</version>
  18. <relativePath/>
  19. </parent>
  20. <properties>
  21. <maven.compiler.source>8</maven.compiler.source>
  22. <maven.compiler.target>8</maven.compiler.target>
  23. </properties>
  24. <dependencies>
  25. <dependency>
  26. <groupId>org.projectlombok</groupId>
  27. <artifactId>lombok</artifactId>
  28. <version>1.18.24</version>
  29. </dependency>
  30. <!--AMQP依赖,包含RabbitMQ-->
  31. <dependency>
  32. <groupId>org.springframework.boot</groupId>
  33. <artifactId>spring-boot-starter-amqp</artifactId>
  34. </dependency>
  35. <!--单元测试-->
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-test</artifactId>
  39. </dependency>
  40. </dependencies>
  41. </project>

2.在publisher服务中利用RabbitTemplate发送消息到simple.queue这个队列

1.在publisher服务中编写application.yml,添加mq连接信息:

spring:
  rabbitmq:
    host: xxx.xxx.xxx.xxx #RabbitMQ的虚拟机ip
    port: 5672 #Rabbit的端口
    username: itcast
    password: 123321
    virtual-host: / #该username的虚拟主机
  1. logging:
  2. pattern:
  3. dateformat: MM-dd HH:mm:ss:SSS
  4. spring:
  5. rabbitmq:
  6. host: xxx.xxx.xxx.xxx #RabbitMQ的虚拟机ip
  7. port: 5672 #Rabbit的端口
  8. username: itcast
  9. password: 123321
  10. virtual-host: / #该username的虚拟主机

 2.在publisher服务中新建一个测试类,编写测试方法:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAmqpTest {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void testSendMessage2SimpleQueue() {
        String queueName = "simple.queue";
        String message = "hello, spring amqp!";
        rabbitTemplate.convertAndSend(queueName,message);
    }

}

  1. package cn.itcast.mq.spring;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.amqp.rabbit.connection.RabbitAccessor;
  5. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.autoconfigure.SpringBootApplication;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import org.springframework.test.context.junit4.SpringRunner;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. @RunWith(SpringRunner.class)
  13. @SpringBootTest
  14. public class SpringAmqpTest {
  15. @Autowired
  16. private RabbitTemplate rabbitTemplate;
  17. @Test
  18. public void testSendMessage2SimpleQueue() {
  19. String queueName = "simple.queue";
  20. String message = "hello, spring amqp!";
  21. rabbitTemplate.convertAndSend(queueName,message);
  22. }
  23. }

运行该测试用例,会看到成功运行

此时在RabbitMQ页面中可以看到simple.queue队列有一条数据

点击simple.queue,进入该服务中看,能看到发送的hello,spring amqp

3.在consumer服务中编写消费逻辑,绑定simple.queue这个队列

1.在consumer服务中编写application.yml,添加mq连接信息:

spring:
  rabbitmq:
    host: xxx.xxx.xxx.xxx #RabbitMQ的虚拟机ip
    port: 5672 #Rabbit的端口
    username: itcast
    password: 123321
    virtual-host: / #该username的虚拟主机
  1. logging:
  2. pattern:
  3. dateformat: MM-dd HH:mm:ss:SSS
  4. spring:
  5. rabbitmq:
  6. host: XXX.XXX.XXX.XXX #RabbitMQ的虚拟机ip
  7. port: 5672 #Rabbit的端口
  8. username: itcast
  9. password: 123321
  10. virtual-host: / #该username的虚拟主机

 2.在consumer服务中新建一个类,编写消费逻辑:

@Component
public class SpringRabbitListener {
    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueue(String msg) {
        System.out.println("消费者接收到simple.queue的消息:【" + msg + "】");
    }

}
  1. package cn.itcast.mq.listener;
  2. import org.springframework.amqp.core.ExchangeTypes;
  3. import org.springframework.amqp.rabbit.annotation.Exchange;
  4. import org.springframework.amqp.rabbit.annotation.Queue;
  5. import org.springframework.amqp.rabbit.annotation.QueueBinding;
  6. import org.springframework.amqp.rabbit.annotation.RabbitListener;
  7. import org.springframework.stereotype.Component;
  8. import java.time.LocalTime;
  9. import java.util.Map;
  10. @Component
  11. public class SpringRabbitListener {
  12. @RabbitListener(queues = "simple.queue")
  13. public void listenSimpleQueue(String msg) {
  14. System.out.println("消费者接收到simple.queue的消息:【" + msg + "】");
  15. }
  16. }

 运行该代码,可以看到运行成功,并接受到了simple.queue中的消息

并且消息也就没了 

模拟WorkQueue,实现一个队列绑定多个消费者:

1.在publisher服务中定义测试方法,每秒产生50条消息,发送到simple.queue

处理消息的发送,发送50条,并有20毫米的延迟,不然太快了

@Test
public void testSendMessage2WorkQueue() throws InterruptedException {
    String queueName = "simple.queue";
    String message = "hello, message__!";
    for(int i=1;i<=50;i++){
        rabbitTemplate.convertAndSend(queueName,message + i);
        Thread.sleep(20);
    }
}
  1. package cn.itcast.mq.spring;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.amqp.rabbit.connection.RabbitAccessor;
  5. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.autoconfigure.SpringBootApplication;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import org.springframework.test.context.junit4.SpringRunner;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. @RunWith(SpringRunner.class)
  13. @SpringBootTest
  14. public class SpringAmqpTest {
  15. @Autowired
  16. private RabbitTemplate rabbitTemplate;
  17. @Test
  18. public void testSendMessage2SimpleQueue() {
  19. String queueName = "simple.queue";
  20. String message = "hello, spring amqp!";
  21. rabbitTemplate.convertAndSend(queueName,message);
  22. }
  23. @Test
  24. public void testSendMessage2WorkQueue() throws InterruptedException {
  25. String queueName = "simple.queue";
  26. String message = "hello, message__!";
  27. for(int i=1;i<=50;i++){
  28. rabbitTemplate.convertAndSend(queueName,message + i);
  29. Thread.sleep(20);
  30. }
  31. }
  32. }

2.在consumer服务中定义两个消息监听者,都监听simple.queue队列,消费者1每秒处理50条消息,消费者2每秒处理10条消息

处理消息的接收,用两个接受者,看看处理的情况

@RabbitListener(queues = "simple.queue")
public void listenWorkQueue1(String msg) throws InterruptedException {
    System.out.println("消费者1接收到消息:【"+ msg + "】" + LocalTime.now());
    Thread.sleep(20);
}

        

@RabbitListener(queues = "simple.queue")
public void listenWorkQueue2(String msg) throws InterruptedException {
    System.err.println("消费者2....接收到消息:【"+ msg + "】" + LocalTime.now());
    Thread.sleep(200);
}
  1. package cn.itcast.mq.listener;
  2. import org.springframework.amqp.core.ExchangeTypes;
  3. import org.springframework.amqp.rabbit.annotation.Exchange;
  4. import org.springframework.amqp.rabbit.annotation.Queue;
  5. import org.springframework.amqp.rabbit.annotation.QueueBinding;
  6. import org.springframework.amqp.rabbit.annotation.RabbitListener;
  7. import org.springframework.stereotype.Component;
  8. import java.time.LocalTime;
  9. import java.util.Map;
  10. @Component
  11. public class SpringRabbitListener {
  12. @RabbitListener(queues = "simple.queue")
  13. public void listenSimpleQueue(String msg) {
  14. System.out.println("消费者接收到simple.queue的消息:【" + msg + "】");
  15. }
  16. @RabbitListener(queues = "simple.queue")
  17. public void listenWorkQueue1(String msg) throws InterruptedException {
  18. System.out.println("消费者1接收到消息:【"+ msg + "】" + LocalTime.now());
  19. Thread.sleep(20);
  20. }
  21. @RabbitListener(queues = "simple.queue")
  22. public void listenWorkQueue2(String msg) throws InterruptedException {
  23. System.err.println("消费者2....接收到消息:【"+ msg + "】" + LocalTime.now());
  24. Thread.sleep(200);
  25. }
  26. }

启动consumer的启动类,再启动publisher的测试类。

此时可以看到,消费者1和消费者2分别处理偶数和奇数的消息。

说明就算消费者2的处理时间是消费者1的十倍,但是它仍然是和消费者1分别拿了一半的消息。

修改consumer的application.yml文件

listener:
  simple:
    prefetch: 1 #每次只取一条,等处理完成后再继续取
  1. logging:
  2. pattern:
  3. dateformat: MM-dd HH:mm:ss:SSS
  4. spring:
  5. rabbitmq:
  6. host: 192.168.80.129 #RabbitMQ的虚拟机ip
  7. port: 5672 #Rabbit的端口
  8. username: itcast
  9. password: 123321
  10. virtual-host: / #该username的虚拟主机
  11. listener:
  12. simple:
  13. prefetch: 1 #每次只取一条,等处理完成后再继续取

重新再运行consumer的启动类和publisher的测试类。此时可以看到消费者2不再跟消费者1一人一半消息了。

发布和订阅:

发布订阅模式与之前案例的区别就是允许将同一消息发送给多个消费者。实现方式是加入了exchange(交换机)。

常见exchange类型包括:
1、Fanout:广播
2、Direct:路由

3、Topic:话题

注意: exchange负责消息路由,而不是存储,路由失败则消息丢失

发布订阅-Fanout Exchange

Fanout Exchange会将接收到的消息路由到每一个跟其绑定的queue

利用SpringAMQP演示FanoutExchange的使用

1.在consumer服务中,利用代码声明队列、交换机,并将两者绑定

在consumer服务常见一个类,添加@Configuration注解,并声明FanoutExchange、Queue和绑定关系对象Binding,代码如下:

@Configuration
public class FanoutConfig {
    //交换机名字:itcast.fanout
    @Bean
    public FanoutExchange fanoutExchange(){
        return new FanoutExchange("itcast.fanout");
    }

    //队列名称: fanout.queue1
    @Bean
    public Queue fanoutQueue1(){
        return new Queue("fanout.queue1");
    }
    //绑定队列1到交换机
    @Bean
    public Binding fanoutBinding1(Queue fanoutQueue1,FanoutExchange fanoutExchange){
        return BindingBuilder.bind(fanoutQueue1).to(fanoutExchange);
    }

    //队列名称: fanout.queue2
    @Bean
    public Queue fanoutQueue2(){
        return new Queue("fanout.queue2");
    }
    //绑定队列2到交换机
    @Bean
    public Binding fanoutBinding2(Queue fanoutQueue2,FanoutExchange fanoutExchange){
        return BindingBuilder.bind(fanoutQueue2).to(fanoutExchange);
    }

  
}
  1. package cn.itcast.mq.config;
  2. import org.springframework.amqp.core.Binding;
  3. import org.springframework.amqp.core.BindingBuilder;
  4. import org.springframework.amqp.core.FanoutExchange;
  5. import org.springframework.amqp.core.Queue;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. @Configuration
  9. public class FanoutConfig {
  10. //交换机名字:itcast.fanout
  11. @Bean
  12. public FanoutExchange fanoutExchange(){
  13. return new FanoutExchange("itcast.fanout");
  14. }
  15. //队列名称: fanout.queue1
  16. @Bean
  17. public Queue fanoutQueue1(){
  18. return new Queue("fanout.queue1");
  19. }
  20. //绑定队列1到交换机
  21. @Bean
  22. public Binding fanoutBinding1(Queue fanoutQueue1,FanoutExchange fanoutExchange){
  23. return BindingBuilder.bind(fanoutQueue1).to(fanoutExchange);
  24. }
  25. //队列名称: fanout.queue2
  26. @Bean
  27. public Queue fanoutQueue2(){
  28. return new Queue("fanout.queue2");
  29. }
  30. //绑定队列2到交换机
  31. @Bean
  32. public Binding fanoutBinding2(Queue fanoutQueue2,FanoutExchange fanoutExchange){
  33. return BindingBuilder.bind(fanoutQueue2).to(fanoutExchange);
  34. }
  35. }

启动consumer的启动类

可以在RabbitMQ的网站上看到这两个队列

可以在RabbitMQ的网站上看到该交换机

点击该交换机,可以看到里面绑定了两个队列

2.在consumer服务中,编写两个消费者方法,分别监听fanout.queue1和fanout.queue2

@RabbitListener(queues = "fanout.queue1")
public void listenFanoutQueue1(String msg)  {
    System.out.println("消费者接收到fanout.queue1的消息:【"+ msg + "】");
}

@RabbitListener(queues = "fanout.queue2")
public void listenFanoutQueue2(String msg)  {
    System.out.println("消费者接收到fanout.queue2的消息:【"+ msg + "】");
}
  1. package cn.itcast.mq.listener;
  2. import org.springframework.amqp.core.ExchangeTypes;
  3. import org.springframework.amqp.rabbit.annotation.Exchange;
  4. import org.springframework.amqp.rabbit.annotation.Queue;
  5. import org.springframework.amqp.rabbit.annotation.QueueBinding;
  6. import org.springframework.amqp.rabbit.annotation.RabbitListener;
  7. import org.springframework.stereotype.Component;
  8. import java.time.LocalTime;
  9. import java.util.Map;
  10. @Component
  11. public class SpringRabbitListener {
  12. // @RabbitListener(queues = "simple.queue")
  13. // public void listenSimpleQueue(String msg) {
  14. // System.out.println("消费者接收到simple.queue的消息:【" + msg + "】");
  15. // }
  16. //
  17. // @RabbitListener(queues = "simple.queue")
  18. // public void listenWorkQueue1(String msg) throws InterruptedException {
  19. // System.out.println("消费者1接收到消息:【"+ msg + "】" + LocalTime.now());
  20. // Thread.sleep(20);
  21. // }
  22. // @RabbitListener(queues = "simple.queue")
  23. // public void listenWorkQueue2(String msg) throws InterruptedException {
  24. // System.err.println("消费者2....接收到消息:【"+ msg + "】" + LocalTime.now());
  25. // Thread.sleep(200);
  26. // }
  27. @RabbitListener(queues = "fanout.queue1")
  28. public void listenFanoutQueue1(String msg) {
  29. System.out.println("消费者接收到fanout.queue1的消息:【"+ msg + "】");
  30. }
  31. @RabbitListener(queues = "fanout.queue2")
  32. public void listenFanoutQueue2(String msg) {
  33. System.out.println("消费者接收到fanout.queue2的消息:【"+ msg + "】");
  34. }
  35. }

3.在publisher中编写测试方法,向itcast.fanout发送消息

@Test
public void testSendFanoutExchange(){
    //交换机名称
    String exchangeName = "itcast.fanout";
    //消息
    String message = "hello,everyone!";
    //发送消息
    rabbitTemplate.convertAndSend(exchangeName,"",message);
}
  1. package cn.itcast.mq.spring;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.amqp.rabbit.connection.RabbitAccessor;
  5. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.autoconfigure.SpringBootApplication;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import org.springframework.test.context.junit4.SpringRunner;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. @RunWith(SpringRunner.class)
  13. @SpringBootTest
  14. public class SpringAmqpTest {
  15. @Autowired
  16. private RabbitTemplate rabbitTemplate;
  17. @Test
  18. public void testSendMessage2SimpleQueue() {
  19. String queueName = "simple.queue";
  20. String message = "hello, spring amqp!";
  21. rabbitTemplate.convertAndSend(queueName,message);
  22. }
  23. @Test
  24. public void testSendMessage2WorkQueue() throws InterruptedException {
  25. String queueName = "simple.queue";
  26. String message = "hello, message__!";
  27. for(int i=1;i<=50;i++){
  28. rabbitTemplate.convertAndSend(queueName,message + i);
  29. Thread.sleep(20);
  30. }
  31. }
  32. @Test
  33. public void testSendFanoutExchange(){
  34. //交换机名称
  35. String exchangeName = "itcast.fanout";
  36. //消息
  37. String message = "hello,everyone!";
  38. //发送消息
  39. rabbitTemplate.convertAndSend(exchangeName,"",message);
  40. }
  41. }

 运行publisher的测试类和consumer的启动类,可以看到两个队列都收到了

发布订阅-DirectExchange

Direct Exchange 会将接收到的消息根据规则路由到指定的Queue,因此称为路由模式(routes)。

1、每一个Queue都与Exchange设置一个BindingKey

2、发布者发送消息时,指定消息的RoutingKey
3、Exchange将消息路由到BindingKey与消息RoutingKey一致的队列

1.利用@RabbitListener声明Exchange、Queue、RoutingKey,在consumer服务中,编写两个消费者方法,分别监听direct.queue1和direct.queue2

@RabbitListener(bindings = @QueueBinding(
        value = @Queue(name = "direct.queue1"),
        exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT),
        key = {"red","blue"}))
public void ListenDirectQueue1(String msg){
    System.out.println("消费者接收到direct.queue1的消息:【"+ msg + "】");
}

@RabbitListener(bindings = @QueueBinding(
        value = @Queue(name = "direct.queue2"),
        exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT),
        key = {"red","yellow"}))
public void ListenDirectQueue2(String msg){
    System.out.println("消费者接收到direct.queue2的消息:【"+ msg + "】");
}
  1. package cn.itcast.mq.listener;
  2. import org.springframework.amqp.core.ExchangeTypes;
  3. import org.springframework.amqp.rabbit.annotation.Exchange;
  4. import org.springframework.amqp.rabbit.annotation.Queue;
  5. import org.springframework.amqp.rabbit.annotation.QueueBinding;
  6. import org.springframework.amqp.rabbit.annotation.RabbitListener;
  7. import org.springframework.stereotype.Component;
  8. import java.time.LocalTime;
  9. import java.util.Map;
  10. @Component
  11. public class SpringRabbitListener {
  12. // @RabbitListener(queues = "simple.queue")
  13. // public void listenSimpleQueue(String msg) {
  14. // System.out.println("消费者接收到simple.queue的消息:【" + msg + "】");
  15. // }
  16. //
  17. // @RabbitListener(queues = "simple.queue")
  18. // public void listenWorkQueue1(String msg) throws InterruptedException {
  19. // System.out.println("消费者1接收到消息:【"+ msg + "】" + LocalTime.now());
  20. // Thread.sleep(20);
  21. // }
  22. // @RabbitListener(queues = "simple.queue")
  23. // public void listenWorkQueue2(String msg) throws InterruptedException {
  24. // System.err.println("消费者2....接收到消息:【"+ msg + "】" + LocalTime.now());
  25. // Thread.sleep(200);
  26. // }
  27. @RabbitListener(queues = "fanout.queue1")
  28. public void listenFanoutQueue1(String msg) {
  29. System.out.println("消费者接收到fanout.queue1的消息:【"+ msg + "】");
  30. }
  31. @RabbitListener(queues = "fanout.queue2")
  32. public void listenFanoutQueue2(String msg) {
  33. System.out.println("消费者接收到fanout.queue2的消息:【"+ msg + "】");
  34. }
  35. @RabbitListener(bindings = @QueueBinding(
  36. value = @Queue(name = "direct.queue1"),
  37. exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT),
  38. key = {"red","blue"}))
  39. public void ListenDirectQueue1(String msg){
  40. System.out.println("消费者接收到direct.queue1的消息:【"+ msg + "】");
  41. }
  42. @RabbitListener(bindings = @QueueBinding(
  43. value = @Queue(name = "direct.queue2"),
  44. exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT),
  45. key = {"red","yellow"}))
  46. public void ListenDirectQueue2(String msg){
  47. System.out.println("消费者接收到direct.queue2的消息:【"+ msg + "】");
  48. }
  49. }

运行consumer的启动类,在RabbitMQ的网页中可以看到多出了itcast.direct的交换机

队列也多出两个direct.queue

 可以看到两个队列分别绑定了两个key

2.在publisher中编写测试方法,向itcast. direct发送消息

@Test
public void testSendDirectExchange(){
    //交换机名称
    String exchangeName = "itcast.direct";
    //消息
    String message = "hello,red!";
    //发送消息
    rabbitTemplate.convertAndSend(exchangeName,"red",message);
}
  1. package cn.itcast.mq.spring;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.amqp.rabbit.connection.RabbitAccessor;
  5. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.autoconfigure.SpringBootApplication;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import org.springframework.test.context.junit4.SpringRunner;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. @RunWith(SpringRunner.class)
  13. @SpringBootTest
  14. public class SpringAmqpTest {
  15. @Autowired
  16. private RabbitTemplate rabbitTemplate;
  17. @Test
  18. public void testSendMessage2SimpleQueue() {
  19. String queueName = "simple.queue";
  20. String message = "hello, spring amqp!";
  21. rabbitTemplate.convertAndSend(queueName,message);
  22. }
  23. @Test
  24. public void testSendMessage2WorkQueue() throws InterruptedException {
  25. String queueName = "simple.queue";
  26. String message = "hello, message__!";
  27. for(int i=1;i<=50;i++){
  28. rabbitTemplate.convertAndSend(queueName,message + i);
  29. Thread.sleep(20);
  30. }
  31. }
  32. @Test
  33. public void testSendFanoutExchange(){
  34. //交换机名称
  35. String exchangeName = "itcast.fanout";
  36. //消息
  37. String message = "hello,everyone!";
  38. //发送消息
  39. rabbitTemplate.convertAndSend(exchangeName,"",message);
  40. }
  41. @Test
  42. public void testSendDirectExchange(){
  43. //交换机名称
  44. String exchangeName = "itcast.direct";
  45. //消息
  46. String message = "hello,red!";
  47. //发送消息
  48. rabbitTemplate.convertAndSend(exchangeName,"red",message);
  49. }
  50. }

通过修改message的内容,绑定了不同key的队列会收到不同的消息

发布订阅-TopicExchange

TopicExchange与DirectExchange类似,区别在于routingKey必须是多个单词的列表,并且以.分割。

Queue与Exchange指定BindingKey时可以使用通配符:

#:代指0个或多个单词
*:代指一个单词

1.并利用@RabbitListener声明Exchange、Queue、RoutingKey,在consumer服务中,编写两个消费者方法,分别监听topic.queue1和topic.queue2

@RabbitListener(bindings = @QueueBinding(
        value = @Queue(name = "topic.queue1"),
        exchange = @Exchange(name = "itcast.topic",type = ExchangeTypes.TOPIC),
        key = "china.#"
))
public void ListenTopictQueue1(String msg){
    System.out.println("消费者接收到topic.queue1的消息:【"+ msg + "】");
}

@RabbitListener(bindings = @QueueBinding(
        value = @Queue(name = "topic.queue2"),
        exchange = @Exchange(name = "itcast.topic",type = ExchangeTypes.TOPIC),
        key = "#.news"
))
public void ListenTopictQueue2(String msg){
    System.out.println("消费者接收到topic.queue2的消息:【"+ msg + "】");
}
  1. package cn.itcast.mq.listener;
  2. import org.springframework.amqp.core.ExchangeTypes;
  3. import org.springframework.amqp.rabbit.annotation.Exchange;
  4. import org.springframework.amqp.rabbit.annotation.Queue;
  5. import org.springframework.amqp.rabbit.annotation.QueueBinding;
  6. import org.springframework.amqp.rabbit.annotation.RabbitListener;
  7. import org.springframework.stereotype.Component;
  8. import java.time.LocalTime;
  9. import java.util.Map;
  10. @Component
  11. public class SpringRabbitListener {
  12. // @RabbitListener(queues = "simple.queue")
  13. // public void listenSimpleQueue(String msg) {
  14. // System.out.println("消费者接收到simple.queue的消息:【" + msg + "】");
  15. // }
  16. //
  17. // @RabbitListener(queues = "simple.queue")
  18. // public void listenWorkQueue1(String msg) throws InterruptedException {
  19. // System.out.println("消费者1接收到消息:【"+ msg + "】" + LocalTime.now());
  20. // Thread.sleep(20);
  21. // }
  22. // @RabbitListener(queues = "simple.queue")
  23. // public void listenWorkQueue2(String msg) throws InterruptedException {
  24. // System.err.println("消费者2....接收到消息:【"+ msg + "】" + LocalTime.now());
  25. // Thread.sleep(200);
  26. // }
  27. @RabbitListener(queues = "fanout.queue1")
  28. public void listenFanoutQueue1(String msg) {
  29. System.out.println("消费者接收到fanout.queue1的消息:【"+ msg + "】");
  30. }
  31. @RabbitListener(queues = "fanout.queue2")
  32. public void listenFanoutQueue2(String msg) {
  33. System.out.println("消费者接收到fanout.queue2的消息:【"+ msg + "】");
  34. }
  35. @RabbitListener(bindings = @QueueBinding(
  36. value = @Queue(name = "direct.queue1"),
  37. exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT),
  38. key = {"red","blue"}))
  39. public void ListenDirectQueue1(String msg){
  40. System.out.println("消费者接收到direct.queue1的消息:【"+ msg + "】");
  41. }
  42. @RabbitListener(bindings = @QueueBinding(
  43. value = @Queue(name = "direct.queue2"),
  44. exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT),
  45. key = {"red","yellow"}))
  46. public void ListenDirectQueue2(String msg){
  47. System.out.println("消费者接收到direct.queue2的消息:【"+ msg + "】");
  48. }
  49. @RabbitListener(bindings = @QueueBinding(
  50. value = @Queue(name = "topic.queue1"),
  51. exchange = @Exchange(name = "itcast.topic",type = ExchangeTypes.TOPIC),
  52. key = "china.#"
  53. ))
  54. public void ListenTopictQueue1(String msg){
  55. System.out.println("消费者接收到topic.queue1的消息:【"+ msg + "】");
  56. }
  57. @RabbitListener(bindings = @QueueBinding(
  58. value = @Queue(name = "topic.queue2"),
  59. exchange = @Exchange(name = "itcast.topic",type = ExchangeTypes.TOPIC),
  60. key = "#.news"
  61. ))
  62. public void ListenTopictQueue2(String msg){
  63. System.out.println("消费者接收到topic.queue2的消息:【"+ msg + "】");
  64. }
  65. }

运行后,在RabbitMQ网页中,可以看到,队列中出现了两个topic.queue

在交换机中也出现了itcas.topic

 点击该交换机,可以看到绑定了两个topic.queue,并且绑定了不同的key。

2.在publisher中编写测试方法,向itcast. topic发送消息

@Test
public void testSendTopicExchange(){
    //交换机名称
    String exchangeName = "itcast.topic";
    //消息
    String message = "天气!";
    //发送消息
    rabbitTemplate.convertAndSend(exchangeName,"china.weather",message);
}
  1. package cn.itcast.mq.spring;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.amqp.rabbit.connection.RabbitAccessor;
  5. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.autoconfigure.SpringBootApplication;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import org.springframework.test.context.junit4.SpringRunner;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. @RunWith(SpringRunner.class)
  13. @SpringBootTest
  14. public class SpringAmqpTest {
  15. @Autowired
  16. private RabbitTemplate rabbitTemplate;
  17. @Test
  18. public void testSendMessage2SimpleQueue() {
  19. String queueName = "simple.queue";
  20. String message = "hello, spring amqp!";
  21. rabbitTemplate.convertAndSend(queueName,message);
  22. }
  23. @Test
  24. public void testSendMessage2WorkQueue() throws InterruptedException {
  25. String queueName = "simple.queue";
  26. String message = "hello, message__!";
  27. for(int i=1;i<=50;i++){
  28. rabbitTemplate.convertAndSend(queueName,message + i);
  29. Thread.sleep(20);
  30. }
  31. }
  32. @Test
  33. public void testSendFanoutExchange(){
  34. //交换机名称
  35. String exchangeName = "itcast.fanout";
  36. //消息
  37. String message = "hello,everyone!";
  38. //发送消息
  39. rabbitTemplate.convertAndSend(exchangeName,"",message);
  40. }
  41. @Test
  42. public void testSendDirectExchange(){
  43. //交换机名称
  44. String exchangeName = "itcast.direct";
  45. //消息
  46. String message = "hello,red!";
  47. //发送消息
  48. rabbitTemplate.convertAndSend(exchangeName,"red",message);
  49. }
  50. @Test
  51. public void testSendTopicExchange(){
  52. //交换机名称
  53. String exchangeName = "itcast.topic";
  54. //消息
  55. String message = "天气!";
  56. //发送消息
  57. rabbitTemplate.convertAndSend(exchangeName,"china.weather",message);
  58. }
  59. }

可以看到,通过修改不同的message,会由不同的队列接收

测试发送Object类型消息

说明:在SpringAMQP的发送方法中,接收消息的类型是Object,也就是说我们可以发送任意对象类型的消息,SpringAMQP会帮我们序列化为字节后发送。

编写一个队列,在FanoutConfig里写

@Bean
public Queue objectQueue(){
    return new Queue("object.queue");
}
  1. package cn.itcast.mq.config;
  2. import org.springframework.amqp.core.Binding;
  3. import org.springframework.amqp.core.BindingBuilder;
  4. import org.springframework.amqp.core.FanoutExchange;
  5. import org.springframework.amqp.core.Queue;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. @Configuration
  9. public class FanoutConfig {
  10. //交换机名字:itcast.fanout
  11. @Bean
  12. public FanoutExchange fanoutExchange(){
  13. return new FanoutExchange("itcast.fanout");
  14. }
  15. //队列名称: fanout.queue1
  16. @Bean
  17. public Queue fanoutQueue1(){
  18. return new Queue("fanout.queue1");
  19. }
  20. //绑定队列1到交换机
  21. @Bean
  22. public Binding fanoutBinding1(Queue fanoutQueue1,FanoutExchange fanoutExchange){
  23. return BindingBuilder.bind(fanoutQueue1).to(fanoutExchange);
  24. }
  25. //队列名称: fanout.queue2
  26. @Bean
  27. public Queue fanoutQueue2(){
  28. return new Queue("fanout.queue2");
  29. }
  30. //绑定队列2到交换机
  31. @Bean
  32. public Binding fanoutBinding2(Queue fanoutQueue2,FanoutExchange fanoutExchange){
  33. return BindingBuilder.bind(fanoutQueue2).to(fanoutExchange);
  34. }
  35. @Bean
  36. public Queue objectQueue(){
  37. return new Queue("object.queue");
  38. }
  39. }

 运行consumer的启动类,在RabbitMQ网页中可以看到object.queue的队列

编写消息

@Test
public void testSendObjectQueue(){
    Map<String,Object> msg = new HashMap<>();
    msg.put("name","小明");
    msg.put("age",21);
    rabbitTemplate.convertAndSend("object.queue",msg);
}
  1. package cn.itcast.mq.spring;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.amqp.rabbit.connection.RabbitAccessor;
  5. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.autoconfigure.SpringBootApplication;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import org.springframework.test.context.junit4.SpringRunner;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. @RunWith(SpringRunner.class)
  13. @SpringBootTest
  14. public class SpringAmqpTest {
  15. @Autowired
  16. private RabbitTemplate rabbitTemplate;
  17. @Test
  18. public void testSendMessage2SimpleQueue() {
  19. String queueName = "simple.queue";
  20. String message = "hello, spring amqp!";
  21. rabbitTemplate.convertAndSend(queueName,message);
  22. }
  23. @Test
  24. public void testSendMessage2WorkQueue() throws InterruptedException {
  25. String queueName = "simple.queue";
  26. String message = "hello, message__!";
  27. for(int i=1;i<=50;i++){
  28. rabbitTemplate.convertAndSend(queueName,message + i);
  29. Thread.sleep(20);
  30. }
  31. }
  32. @Test
  33. public void testSendFanoutExchange(){
  34. //交换机名称
  35. String exchangeName = "itcast.fanout";
  36. //消息
  37. String message = "hello,everyone!";
  38. //发送消息
  39. rabbitTemplate.convertAndSend(exchangeName,"",message);
  40. }
  41. @Test
  42. public void testSendDirectExchange(){
  43. //交换机名称
  44. String exchangeName = "itcast.direct";
  45. //消息
  46. String message = "hello,red!";
  47. //发送消息
  48. rabbitTemplate.convertAndSend(exchangeName,"red",message);
  49. }
  50. @Test
  51. public void testSendTopicExchange(){
  52. //交换机名称
  53. String exchangeName = "itcast.topic";
  54. //消息
  55. String message = "天气!";
  56. //发送消息
  57. rabbitTemplate.convertAndSend(exchangeName,"china.weather",message);
  58. }
  59. @Test
  60. public void testSendObjectQueue(){
  61. Map<String,Object> msg = new HashMap<>();
  62. msg.put("name","小明");
  63. msg.put("age",21);
  64. rabbitTemplate.convertAndSend("object.queue",msg);
  65. }
  66. }

启动该测试类,在RabbitMQ网页中可以看到object.queue已经有新的消息

点击该队列,看到消息变成了奇怪的序列化

 消息转换器

Spring的对消息对象的处理是由org.springframework.amqp.support.converter.MessageConverter来处理的。而默认实现是SimpleMessageConverter,基于JDK的ObjectOutputStream完成序列化。
如果要修改只需要定义一个MessageConverter类型的Bean即可。推荐用JSON方式序列化

在mq-demo的pom文件中添加:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>cn.itcast.demo</groupId>
  7. <artifactId>mq-demo</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <modules>
  10. <module>publisher</module>
  11. <module>consumer</module>
  12. </modules>
  13. <packaging>pom</packaging>
  14. <parent>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-parent</artifactId>
  17. <version>2.3.9.RELEASE</version>
  18. <relativePath/>
  19. </parent>
  20. <properties>
  21. <maven.compiler.source>8</maven.compiler.source>
  22. <maven.compiler.target>8</maven.compiler.target>
  23. </properties>
  24. <dependencies>
  25. <dependency>
  26. <groupId>org.projectlombok</groupId>
  27. <artifactId>lombok</artifactId>
  28. <version>1.18.24</version>
  29. </dependency>
  30. <!--AMQP依赖,包含RabbitMQ-->
  31. <dependency>
  32. <groupId>org.springframework.boot</groupId>
  33. <artifactId>spring-boot-starter-amqp</artifactId>
  34. </dependency>
  35. <!--单元测试-->
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-test</artifactId>
  39. </dependency>
  40. <dependency>
  41. <groupId>com.fasterxml.jackson.core</groupId>
  42. <artifactId>jackson-databind</artifactId>
  43. </dependency>
  44. </dependencies>
  45. </project>

在publisher的启动类声明一个bean

@Bean
public MessageConverter messageConverter(){
    return new Jackson2JsonMessageConverter();
}
  1. package cn.itcast.mq;
  2. import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
  3. import org.springframework.amqp.support.converter.MessageConverter;
  4. import org.springframework.boot.SpringApplication;
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;
  6. import org.springframework.context.annotation.Bean;
  7. @SpringBootApplication
  8. public class PublisherApplication {
  9. public static void main(String[] args) {
  10. SpringApplication.run(PublisherApplication.class);
  11. }
  12. @Bean
  13. public MessageConverter messageConverter(){
  14. return new Jackson2JsonMessageConverter();
  15. }
  16. }

 启动测试类,可以看到该内容是正常的了

在consumer中,同样是声明bean,再写一个监听的函数

@Bean
public MessageConverter messageConverter(){
    return new Jackson2JsonMessageConverter();
}
  1. package cn.itcast.mq;
  2. import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
  3. import org.springframework.amqp.support.converter.MessageConverter;
  4. import org.springframework.boot.SpringApplication;
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;
  6. import org.springframework.context.annotation.Bean;
  7. @SpringBootApplication
  8. public class ConsumerApplication {
  9. public static void main(String[] args) {
  10. SpringApplication.run(ConsumerApplication.class, args);
  11. }
  12. @Bean
  13. public MessageConverter messageConverter(){
  14. return new Jackson2JsonMessageConverter();
  15. }
  16. }
@RabbitListener(queues = "object.queue")
public void listenObjectQueue(Map<String,Object> msg){
    System.out.println("接收到object.queue的消息:" + msg);
}
  1. package cn.itcast.mq.listener;
  2. import org.springframework.amqp.core.ExchangeTypes;
  3. import org.springframework.amqp.rabbit.annotation.Exchange;
  4. import org.springframework.amqp.rabbit.annotation.Queue;
  5. import org.springframework.amqp.rabbit.annotation.QueueBinding;
  6. import org.springframework.amqp.rabbit.annotation.RabbitListener;
  7. import org.springframework.stereotype.Component;
  8. import java.time.LocalTime;
  9. import java.util.Map;
  10. @Component
  11. public class SpringRabbitListener {
  12. // @RabbitListener(queues = "simple.queue")
  13. // public void listenSimpleQueue(String msg) {
  14. // System.out.println("消费者接收到simple.queue的消息:【" + msg + "】");
  15. // }
  16. //
  17. // @RabbitListener(queues = "simple.queue")
  18. // public void listenWorkQueue1(String msg) throws InterruptedException {
  19. // System.out.println("消费者1接收到消息:【"+ msg + "】" + LocalTime.now());
  20. // Thread.sleep(20);
  21. // }
  22. // @RabbitListener(queues = "simple.queue")
  23. // public void listenWorkQueue2(String msg) throws InterruptedException {
  24. // System.err.println("消费者2....接收到消息:【"+ msg + "】" + LocalTime.now());
  25. // Thread.sleep(200);
  26. // }
  27. @RabbitListener(queues = "fanout.queue1")
  28. public void listenFanoutQueue1(String msg) {
  29. System.out.println("消费者接收到fanout.queue1的消息:【"+ msg + "】");
  30. }
  31. @RabbitListener(queues = "fanout.queue2")
  32. public void listenFanoutQueue2(String msg) {
  33. System.out.println("消费者接收到fanout.queue2的消息:【"+ msg + "】");
  34. }
  35. @RabbitListener(bindings = @QueueBinding(
  36. value = @Queue(name = "direct.queue1"),
  37. exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT),
  38. key = {"red","blue"}))
  39. public void ListenDirectQueue1(String msg){
  40. System.out.println("消费者接收到direct.queue1的消息:【"+ msg + "】");
  41. }
  42. @RabbitListener(bindings = @QueueBinding(
  43. value = @Queue(name = "direct.queue2"),
  44. exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT),
  45. key = {"red","yellow"}))
  46. public void ListenDirectQueue2(String msg){
  47. System.out.println("消费者接收到direct.queue2的消息:【"+ msg + "】");
  48. }
  49. @RabbitListener(bindings = @QueueBinding(
  50. value = @Queue(name = "topic.queue1"),
  51. exchange = @Exchange(name = "itcast.topic",type = ExchangeTypes.TOPIC),
  52. key = "china.#"
  53. ))
  54. public void ListenTopictQueue1(String msg){
  55. System.out.println("消费者接收到topic.queue1的消息:【"+ msg + "】");
  56. }
  57. @RabbitListener(bindings = @QueueBinding(
  58. value = @Queue(name = "topic.queue2"),
  59. exchange = @Exchange(name = "itcast.topic",type = ExchangeTypes.TOPIC),
  60. key = "#.news"
  61. ))
  62. public void ListenTopictQueue2(String msg){
  63. System.out.println("消费者接收到topic.queue2的消息:【"+ msg + "】");
  64. }
  65. @RabbitListener(queues = "object.queue")
  66. public void listenObjectQueue(Map<String,Object> msg){
  67. System.out.println("接收到object.queue的消息:" + msg);
  68. }
  69. }

 启动consumer的启动类,可以看到成功接收到消息

代码文件点击下载icon-default.png?t=N7T8https://pan.baidu.com/s/1wXL7uWpLXu7X-OWuUZRUKA?pwd=tnxl 上一篇:RabbitMQ的安装和使用

下一篇:ES的安装和RestClient的操作

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/766675
推荐阅读
相关标签
  

闽ICP备14008679号