安装配置参考:https://blog.csdn.net/qq_31634461/article/details/79377256
概念学习参考(纯洁的微笑):https://www.cnblogs.com/ityouknow/p/6120544.html
RabbitMQ的hello world(基于Spring Boot)
1.配置文件
spring.application.name=rabbitMQ spring.rabbitmq.host=127.0.0.1 spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest
2.配置队列
@Configuration public class RabbitMQConfig { @Bean public Queue queue() {
//队列名称,后面生产者根据此队列名称发送消息,消费者也监听此名称 return new Queue("hello"); } }
3.生产者
@Component
public class RabbitMQSender {
//AmqpTemplate接口,spring boot会去实现它
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String info = "hello RabbitMQ!";
System.out.println("send:" + info);
//参数"hello"对应队列的名称
rabbitTemplate.convertAndSend("hello", info);
}
}
4.消费者
@Component @RabbitListener(queues="hello") //监听队列"hello" public class RabbitMQReceiver {
//调用队列的信息,参数hello既是消费的信息; @RabbitHandler public void receive(String hello) { System.out.println("receive:" + hello); } }
5.test
@RunWith(SpringRunner.class) @SpringBootTest public class RabbitMqApplicationTests { @Autowired private RabbitMQSender rabbitMQSender; @Test public void contextLoads2() { rabbitMQSender.send(); } }
结果:
send:hello RabbitMQ!
receive:hello RabbitMQ!
RabbitMQ的交换机与Topic
交换机的作用是接收消息,并转发到绑定的队列,四种类型:Direct, Topic, Headers and Fanout
最灵活的就是Topic
给队列绑定routing_key(路由key),发送消息时,就根据发送消息传回的参数去匹配这个routing_key,然后根据匹配情况把消息分配到对应的消息队列中