1. 交换机
2. Fanout交换机
广播。生产者向exchange发消息
@SpringBootTest
public class SpringAmqpTest {
@Autowired
public RabbitTemplate rabbitTemplate;
@Test
void testSimple() {
String exchangName = "hmall.fabout";
rabbitTemplate.convertAndSend(exchangName, null,"hello, w");
}
}
消费者监听exchange绑定的队列即可。
@Component
@Slf4j
public class SpringAmqbListener {
@Autowired
RabbitTemplate rabbitTemplate;
@RabbitListener(queues = "simple.queue")
public void Lister(String msg) {
log.info(msg);
}
@RabbitListener(queues = "fanout.q1")
public void Lister1(String msg) {
System.out.println("q1:" + msg);
}
@RabbitListener(queues = "fanout.q2")
public void Lister2(String msg) {
System.out.println("q2:" + msg);
}
}
3. Direct 直连交换机
生产者,需要指定exchange和key
@SpringBootTest
public class SpringAmqpTest {
@Autowired
public RabbitTemplate rabbitTemplate;
@Test
void testSimple() {
String exchangName = "hmall.direct";
rabbitTemplate.convertAndSend(exchangName, "yellow", "hello, w");
}
}
消费者指定对列
@Component
@Slf4j
public class SpringAmqbListener {
@Autowired
RabbitTemplate rabbitTemplate;
@RabbitListener(queues = "simple.queue")
public void Lister(String msg) {
log.info(msg);
}
@RabbitListener(queues = "direct.q1")
public void Lister1(String msg) {
System.out.println("q1:" + msg);
}
@RabbitListener(queues = "direct.q2")
public void Lister2(String msg) {
System.out.println("q2:" + msg);
}
@RabbitListener(queues = "direct.q3")
public void Lister3(String msg) {
System.out.println("q3" + msg);
}
}
4. Topic交换机
生产者
@SpringBootTest
public class SpringAmqpTest {
@Autowired
public RabbitTemplate rabbitTemplate;
@Test
void testSimple() {
String exchangName = "hmall.topic";
rabbitTemplate.convertAndSend(exchangName, "china.news", "hello, w");
}
}
消费者
@RabbitListener(queues = "topic.q1")
public void topicLister1(String msg) {
System.out.println("q1:" + msg);
}
@RabbitListener(queues = "topic.q2")
public void topicLister2(String msg) {
System.out.println("q2:" + msg);
}
5. 代码生成交换机
基于注解绑定,在消费者的@Component中写。
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "direct.queue1"),
exchange = @Exchange(name = "hmall.direct", type = ExchangeTypes.DIRECT),
key = {"red", "yellow"}
))
public void topicLister1(String msg) {
System.out.println("q1:" + msg);
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "direct.queue2"),
exchange = @Exchange(name = "hmall.direct", type = ExchangeTypes.DIRECT),
key = {"red", "yellow"}
))
public void topicLister2(String msg) {
System.out.println("q2:" + msg);
}
6. 修改默认序列化器
- 依赖
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
- 注册为Bean
@Bean
public MessageConverter messageConverter() {
return new Jackson2JsonMessageConverter();
}
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » 【RabbitMQ】03-交换机
发表评论 取消回复