RabbitMQ直接模式(Direct)

2.2 直接模式(Direct)

2.2.1 什么是Direct模式

我们需要将消息发给唯一一个节点时使用这种模式,这是最简单的一种形式。

任何发送到Direct Exchange的消息都会被转发到RouteKey中指定的Queue。

1.一般情况可以使用rabbitMQ自带的Exchange:”"(该Exchange的名字为空字符串,下文称其为default Exchange)。

2.这种模式下不需要将Exchange进行任何绑定(binding)操作

3.消息传递时需要一个“RouteKey”,可以简单的理解为要发送到的队列名字。

4.如果vhost中不存在RouteKey中指定的队列名,则该消息会被抛弃。

2.2.2 创建队列

做下面的例子前,我们先建立一个叫test1的队列。

Durability:是否做持久化 Durable(持久) transient(临时)

Auto delete : 是否自动删除

2.2.3 代码实现-消息生产者

(1)创建工程rabbitmq_demo,引入amqp起步依赖 ,pom.xml如下:

<parent>     

<groupId>org.springframework.boot</groupId>         

<artifactId>spring‐boot‐starter‐parent</artifactId>         

<version>2.0.1.RELEASE</version>         

<relativePath/>          

</parent>     

<properties>     

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<java.version>1.8</java.version>         

</properties>     

<dependencies>     

<dependency>         

<groupId>org.springframework.boot</groupId>             

<artifactId>spring-boot-starter-amqp</artifactId>             

</dependency>         

<dependency>         

<groupId>org.springframework.boot</groupId>             

<artifactId>spring-boot-starter-test</artifactId>             

<scope>test</scope>             

</dependency>

</dependencies>

(2)编写配置文件application.yml

 spring:

  rabbitmq:

    host: 192.168.184.134

(3)编写启动类

@SpringBootApplication

public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class);

    }

}

(4)编写测试类

@RunWith(SpringRunner.class)

@SpringBootTest(classes=Application.class)

public class MqTest {

    @Autowired

    private RabbitTemplate rabbitTemplate;

    @Test

    public void testSend(){

        rabbitTemplate.convertAndSend("test1","我要红包");

    }

}

运行测试方法

2.2.4 代码实现-消息消费者

(1)编写消息消费者类

@Component

@RabbitListener(queues="test1" )

public class Customer1 {

    @RabbitHandler

    public void showMessage(String message){

        System.out.println("itcast接收到消息:"+message);

    }

}

(2)运行启动类,可以在控制台看到刚才发送的消息

2.2.5 测试

开启多个消费者工程,测试运行消息生产者工程,会发现只有一个消费者工程可以接收

到消息。

如何在IDEA中多次启动同一个程序呢?

(1)选择IDEA右上角的类名称按钮

(2)选择Edit Configurations

(3)在弹出窗口中取消单例模式 ,点击OK

server: 

  port: 9202

运行后在控制台可以看到多个窗口

猜你喜欢

转载自blog.csdn.net/aileitianshi/article/details/83053507