个人印象笔记地址:https://app.yinxiang.com/fx/c19556bc-e80f-4f4c-bf1f-04595af67180
项目github地址:https://github.com/ztb0312/southwind.git
SpringBoot整合RabbitMQ
搭建初始环境
1. 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.设置yml文件
spring:
application:
name: rabbitmq-springboot
rabbitmq:
host: 192.168.64.130
port: 5672
username: ems
password: 123456
virtual-host: /ems
注意:
消息模板-RabbitTemplate
RabbitTemplate是我们在与SpringAMQP整合的时候进行发送消息的关键类
该类提供了丰富的发送消息的方法,包括可靠性消息投递、回调监听消息接口ConfirmCallback、返回值确认接口
ReturnCallback等等同样我们需要注入到Spring容器中,然后直接使用。
第一种模型: 一对一模型(直连模型)
新建测试类:
package com.ztb.test;
import com.ztb.RabbitmqSpringbootApplication;
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.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = RabbitmqSpringbootApplication.class)
@RunWith(SpringRunner.class)
public class TestRabbitMQ {
//注入rabbitTemplet工具
@Autowired
private RabbitTemplate rabbitTemplate;
//写一个helloworld
@Test
public void test(){
rabbitTemplate.convertAndSend("hello","hello word");
}
}
新建消费者类:
package com.ztb.entity;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(queuesToDeclare = @Queue("hello"))
//启动队列监听 ,queuesToDeclare 声明队列
public class HelloConsumer {
@RabbitHandler
public void recievel(String message){//随便指定一个方法
System.out.println("message======="+message);
}
}
测试结果: