<!--AMQP依赖,包含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>
(1)配置基本mq信息(这里的host指的是我的虚拟机地址)。
spring:
rabbitmq:
host: 192.168.6.130
port: 5672
username: xiaoze
password: 123321
virtual-host: /
(2)编写单元测试用来发送消息
package cn.itcast.mq.spring;
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;
/**
* @author 小泽
* @create 2022-04-21 10:27
* 记得每天敲代码哦
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAmqpTest {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void testSendMessage2SimpleQueue(){
String queueName = "simple.queue";
String message = "hello,spring amqp";
rabbitTemplate.convertAndSend(queueName, message);
}
}
(1)配置mq基本信息,和发布者的一样。
(2)编写监听器,用来监听发布者发布的通道信息。(这里@RabbitListener中可以同时监听多个管道,这里为了测试只监听了一个。名为(simple.queue))
package cn.itcast.mq.listener;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* @author 小泽
* @create 2022-04-21 11:17
* 记得每天敲代码哦
*/
@Component
public class SpringRabbitListener {
@RabbitListener(queues = {"simple.queue"})
public void listenSimpleQueue(String msg){
System.out.println("消费者接收到simple.queue的消息:"+msg);
}
}