1.pom引入依赖:
引入依赖后:容器中自动配置RabbitTemplate、AmqpAdmin、CachingConnectionFactory、RabbitMessagingTemplate
org.springframework.boot
spring-boot-starter-amqp
2.启动类添加@EnableRabbit
3.配置文件,配置rabbit地址,端口5672,账号和密码,虚拟主机配置
4.创建交换机exchange,队列queue,binding,发送消息及接收消息。
创建exchange
//创建交换机 使用AmqpAdmin
@Test
public void createExchange(){
DirectExchange directExchange = new DirectExchange(
"hello-java-exchange",//交换机的名字
true, //持久化,服务器重启也不会消失
false); //不自动删除
amqpAdmin.declareExchange(directExchange);
log.info("Exchange[{}]创建成功:{}","hello-java-exchange","ha");
}
创建队列
//创建队列 使用AmqpAdmin
@Test
public void createQueue(){
Queue queue = new Queue("hello-java-queue",
true, //持久化的 不然关机就没了
false, //不排他 所有人都可以连接
false);//不自动删除
amqpAdmin.declareQueue(queue);
log.info("Exchange[{}]创建成功:{}","hello-java-queue","ha");
}
创建binding
//绑定
@Test
public void createBinding(){
Binding binding = new Binding("hello-java-queue", //目的地,可以使队列或者交换机
Binding.DestinationType.QUEUE, //目的地的种类
"hello-java-exchange", //交换机
"hello.java", //路由键,决定交换机绑定哪个队列
null);//自定义参数
amqpAdmin.declareBinding(binding);
}
发送消息
//发送消息使用RabbitTemplate
@Autowired
RabbitTemplate rabbitTemplate;
@GetMapping("/sendMq")
public String sendMessageTest() {
for (int i = 0; i < 10; i++) {
if(i%2==0){
OrderReturnReasonEntity reasonEntity = new OrderReturnReasonEntity();
reasonEntity.setId(1L);
reasonEntity.setCreateTime(new Date());
reasonEntity.setName("哈哈"+i);
String msg = "Hello World";
//1、发送消息,如果发送的消息是个对象,会使用序列化机制,将对象写出去,对象必须实现Serializable接口
//2、发送的对象类型的消息,可以是一个json
rabbitTemplate.convertAndSend(
"hello-java-exchange",//交换机名字
"hello.java", //路由键,决定交换机把消息传给哪个队列
reasonEntity,//发送的消息为对象
new CorrelationData(UUID.randomUUID().toString()));//消息的唯一id
}else{
OrderEntity orderEntity = new OrderEntity();
orderEntity.setOrderSn(UUID.randomUUID().toString());
//1、发送消息,如果发送的消息是个对象,会使用序列化机制,将对象写出去,对象必须实现Serializable接口
//2、发送的对象类型的消息,可以是一个json
rabbitTemplate.convertAndSend(
"hello-java-exchange",
"hello.java",
orderEntity,
new CorrelationData(UUID.randomUUID().toString()));
}
}
return "ok";
}
发送的消息类型为对象时,需要将序列化后的数据转为json
@Configuration
public class MyRabbitConfig {
@Bean
public MessageConverter messageConverter(){
return new Jackson2JsonMessageConverter();
}
}
接收消息,监听消息
//参数类型可以是message 实体类 channel
@RabbitHandler
public void revieveMessage(Message message,
OrderReturnReasonEntity content,
Channel channel) {
//拿到主体内容
byte[] body = message.getBody();
//拿到的消息头属性信息
MessageProperties messageProperties = message.getMessageProperties();
System.out.println("接受到的消息...内容" + message + "===内容:" + content);
}
@RabbitHandler
public void revieveMessage(OrderEntity orderEntity) {
System.out.println("接受到的消息...内容" + orderEntity);
}
@RabbitHandler 可以接收特定对象 只能用在方法上
@RabbitListener(queues = {“hello-java-queue”}) 接收指定队列的消息 用在类上



