1、消息生产端
1、新建一个maven项目,并导入依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<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>
</dependency>
</dependencies>
2、配置yaml
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
virtual-host: / #虚拟主机
3、编写配置类(通配符模式)
@Configuration
public class RabbitMQConfig {
//交换机名称
public static final String EXCHANGE_NAME = "boot_topic_exchange";
//队列名称
public static final String QUEUE_NAME = "boot_queue";
//交换机
@Bean("bootExchange")
public Exchange bootExchange(){
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
}
//Queue队列
@Bean("bootQueue")
public Queue bootQueue(){
return QueueBuilder.durable(QUEUE_NAME).build();
}
//队列和交换机绑定关系 Binding
/**
* 参数1:哪个交换机(指向我们上面声明的bean)
* 参数2:哪个队列(指向我们上面声明的bean)
* routing Key
*/
public Binding bingQueueExchange(@Qualifier("bootQueue") Queue queue,
@Qualifier("bootExchange") Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs(); //noargs表示没有其他参数
}
}
2、消息接收端
1、新建一个maven项目,并导入依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<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>
</dependency>
</dependencies>
2、配置yaml
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
virtual-host: / #虚拟主机
3、编写监听类
@Component
public class RabbitmqListener {
@RabbitListener(queues = "boot_queue")
public void listenerQueue(Message message){
System.out.println(message);
}
}
完成!!!