什么是AMQP
SpringAMQP实现消息的发送
#####依赖
<!--AMQP依赖,包含RabbitMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
配置文件
spring:
rabbitmq:
host: 47.104.178.202
port: 5672 #rabbitMq的端口,并非15672,云服务器记得打开安全组
username: admin
password: admin
virtual-host: /
消息发送–生产者
使用RabbitTemplate
发送消息
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAmqpTest {
@Autowired
private RabbitTemplate template;
@Test
public void testSendMessage() {
String queueName = "simplequeue";
String message = "hello ,Spring amqp";
template.convertAndSend(queueName,message);
}
}
消息接受–消费者
配置相同的配置文件:
spring:
rabbitmq:
host: 47.104.178.202
port: 5672 #rabbitMq的端口,并非15672,云服务器记得打开安全组
username: admin
password: admin
virtual-host: /
监听类
//交给spring管理
@Component
public class SpringRabbitListener {
//监听simplequeue队列,队列中有消息就接受到,输出
@RabbitListener(queues = "simplequeue")
public void listenSimpleQueue(String msg) {
System.out.println("【接受到消息】:" + msg);
}
}
启动Springboot项目
启动Springboot项目之后,Spring会自动加载我们上述配置的Component,并且会自动监听队列的变化:
此时,如果我们再次运行发送消息的测试方法,在消息接受的方法中会自动打印出再次发送的消息: