**第一步:**添加依赖
pom.xml如下:
4.0.0
pom
org.springframework.boot
spring-boot-starter-parent
2.1.7.RELEASE
名字河蟹了
springboot1-rabbitmq
1.0-SNAPSHOT
//整合rabbitmq的核心包
org.springframework.boot
spring-boot-starter-amqp
org.springframework.boot
spring-boot-devtools
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
第二步
application.yml配置:
spring:
#整合mq
rabbitmq:
#注意设置自己的ip
host: 192.168.223.201
port: 5672
virtual-host: /qq
username: admin
password: admin
#配置的是等会儿要用的amqp模板
template:
retry:
enabled: true
initial-interval: 2s
#配置的是监听者,即消息接受者
listener:
direct:
retry:
enabled: true
initial-interval: 2s
#配置的时候要注意层级关系.listener是rabbitmq的下一级
第三步SpringBoot启动类
代码:
package spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import spring.sender.Sender;
@SpringBootApplication
public class SpringBootRun {
public static void main(String [] args){
SpringApplication.run(SpringBootRun.class,args);
}
}
第四步获取一个队列Bean
package spring.sender;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class QueueA {
//该方法获取一个叫做someQueue的队列
@Bean
Queue getQueue(){
return new Queue(“someQueue”);
}
}
第五步定义一个消息发送者
代码:
package spring.sender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Sender {
//重要!!!spring官方提供的模板.
@Autowired
AmqpTemplate amqpTemplate;
public void send(){
for (int i= 0 ; i< 10 ;i++ ){
//向第四步的someQueue队列发送消息,内容为"再测试一下"
amqpTemplate.convertAndSend("someQueue","再测试一下"+i);
}
}
}
第六步再来一个消息监听者(即消息的消费者)
代码:
package spring.listener;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Listener {
@Autowired
AmqpTemplate amqpTemplate;
//注意:注解里面的queues必须要加上
@RabbitListener(queues = “someQueue”)
private void listen(String msg) {
//打印监控到的消息
System.out.println(“监听者收到数据:”+msg);
}
}
第七步开始测试:
package spring.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import spring.sender.Sender;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SenderTest {
@Autowired
Sender sender;
@Test
public void go(){
sender.send();
}
}
//注意:测试之前,先用主类SpringBootRun启动服务,让服务先跑一边,看是否有Bean没初始化.