写在前面
MQ的应用场景:https://www.aquestian.cn/article/27,请查看这篇文章!
MQ环境搭建:https://www.aquestian.cn/article/28,请查看这篇文章!
环境搭建
1.搭建一个springboot项目。
2.pom引入,mq所需jar包。
<!--rabbitMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
3.yaml配置
spring:
rabbitmq:
host: 127.0.0.1 # rabbitmq的连接地址
port: 5672 # rabbitmq的连接端口号
username: username # rabbitmq的用户名
password: password # rabbitmq的密码
普通模式
简单模式是最简单的消息模式,它包含一个生产者、一个消费者和一个队列。生产者向队列里发送消息,消费者从队列中获取消息并消费。
声明一个队列
@Configuration
public class RabbitConfig {
//申明第一个队列
@Bean
public Queue helloQueue() {
return new Queue("hello");
}
}
创建一个生产者(发送者)
@Component
public class SenderConfig {
@Resource
private AmqpTemplate rabbitTemplate;
//创建消息发送者
public void send() {
String context = "普通模式发送的消息";
System.out.println("普通模式发送者: " + context);
this.rabbitTemplate.convertAndSend("hello", context);
}
}
创建一个消费者(接受者)
@Component
public class ReceiverConfig {
//创建消息接收者
@RabbitListener(queues = "hello")
@RabbitHandler
public void process1(String hello) {
System.err.println("普通模式消费者: " + hello);
}
}
测试一下
@SpringBootTest
public class RabbitDemoApplicationTests {
@Resource
private SenderConfig senderConfig;
@Test
public void contextLoads() {
senderConfig.send();
}
}