MQ
MQ相关技术对比

RabbitMQ


SpringAMQP介绍

SpringAMQP实现基础消息队列功能

- 父工程引入依赖
<!--AMQP依赖,包含RabbitMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
- publisher中application.yml添加mq连接信息以及代码实例
spring:
rabbitmq:
host: 43.143.131.78 # rabbitMQ的ip地址
port: 5672 #rabbitMQ的端口
username: itcast
password: 123321
virtual-host: /
@RunWith(SpringRunner.class)
@SpringBootTest
public class PublisherTest {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void testSendMessage() throws IOException, TimeoutException {
String queueName = "simple.queue";
String message = "hello, spring amqp!";
rabbitTemplate.convertAndSend(queueName, message);
}
}
- 在consumer中编写消费逻辑,监听sample.queue
spring:
rabbitmq:
host: 43.143.131.78 # rabbitMQ的ip地址
port: 5672 #rabbitMQ的端口
username: itcast
password: 123321
virtual-host: /
@Component
public class SpringRabbitListener {
@RabbitListener(queues = "simple.queue")
public void listenSimpleQueue(String msg) {
System.out.println(msg);
}
}
eg: work queue
业务场景:



发布订阅模型

- fanout exchange
1.1 概念
![image]()
1.2 实现
步骤一 声明exchange, queue, binding:
![image]()
@Configuration
public class FanoutConfig {
// 交换机声明
@Bean
public FanoutExchange fanoutExchange() {
return new FanoutExchange("itcast.fanout");
}
// 声明队列
@Bean
public Queue fanoutQueue1() {
return new Queue("fanout.queue1");
}
// 绑定队列1到交换机
@Bean
public Binding fanoutBinding1(Queue fanoutQueue1, FanoutExchange fanoutExchange) {
return BindingBuilder
.bind(fanoutQueue1)
.to(fanoutExchange);
}
}
步骤二 声明消费者
步骤三 发送消息给exchange:
String exchangeName = "itcast.fanout";
String message = "hello, message";
rabbitTemplate.convertAndSend(exchangeName, "", message);
1.3 总结

2. DirectExchange
2.1 介绍

2.2 实现
这次使用@RabbitListener实现(较为方便)
consumer
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "direct.queue1"),
exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT),
key = {"red", "blue"}
))
public void ListenDirectQueue1(String msg) {
System.out.println("消费者1" + msg);
}
publisher
rabbitTemplate.convertAndSend(exchangeName, "red", message);
- Topic Exchange
3.1 介绍
![image]()
3.2 实现
consumer
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "topic.queue1"),
exchange = @Exchange(name = "itcast.topic"),
key = "china.#"
))
public void ListenTopicQueue1(String msg) {
System.out.println("china---" + msg);
}
publisher
@Test
public void testSendMessage() throws IOException, TimeoutException, InterruptedException {
String exchangeName = "itcast.topic";
String message = "hello, china.news";
rabbitTemplate.convertAndSend(exchangeName, "china.news", message);
}




浙公网安备 33010602011771号