maven引入依赖
父工程依赖
<!--
1. 父工程依赖
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
</parent>
<dependencies>
<!--2. rabbitmq-->
<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>
application.yml配置文件 配置连接信息
首先 你要知道默认的guest账户 不支持远程连接 需要创建新用户 并指定管理员角色
spring:
rabbitmq:
host: 192.168.137.150
port: 5677
username: admin
password: 123456
virtual-host: /
配置类 配置消息队列 不同模式的交换机 绑定交换机和消息队列并设置路由key
当前配置一个消息队列 和一个通配符模式的交换机 并将它们进行绑定
package com.atguigu.config;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
@SpringBootConfiguration
public class RabbitMQConfig {
@Bean(name = "boot_exchange")
public Exchange createExchange(){
return ExchangeBuilder.topicExchange("boot_exchange").durable(true).build();
}
@Bean(name = "boot_queue")
public Queue createQueue(){
return QueueBuilder.durable("boot_queue").build();
}
@Bean
public Binding createBinding(@Qualifier("boot_queue") Queue queue,@Qualifier("boot_exchange") Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
}
}
创建生产者 给消息队列发消息
package com.guigu.test;
import com.atguigu.ProducerApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
//当前这两个注解 因为是在测试类中 需要用到spring ioc 容器里面的对象 所以需要配置以spring的方式启动 然后加载springboot 里面有好多的配置类 会产生相对应的对象
@RunWith(SpringRunner.class)
//指定当前启动类是哪个类 如果测试类跟启动类在相同名称的包下
@SpringBootTest(classes= ProducerApplication.class)
public class ProducerTest {
@Autowired
RabbitTemplate rabbitTemplate;
@Test
public void testSend(){
//这里设置向那个叫交换机发送消息 交换机跟消息队列的路由key 和消息本体
rabbitTemplate.convertAndSend("boot_exchange","boot.hehe","spring boot info...");
}
}
监听者【消费者】接受消息队列的信息
package com.atguigu.listener;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
//将此对象加入到 spring容器中
@Component
public class RabbimtMQListener {
//这个注解 配置当前监听器监听的消息队列的名称 自动监听交换机的队列 这个注解里面还有很多参数 建议进入源代码 学习和百度一下
@RabbitListener(queues = "boot_queue")
public void msg(Message message){
System.out.println("message = " + message);
}
}