1. 交换机
2. Fanout交换机
广播。生产者向exchange发消息
@SpringBootTest
public class SpringAmqpTest {@Autowiredpublic RabbitTemplate rabbitTemplate;@Testvoid testSimple() {String exchangName = "hmall.fabout";rabbitTemplate.convertAndSend(exchangName, null,"hello, w");}
}
消费者监听exchange绑定的队列即可。
@Component
@Slf4j
public class SpringAmqbListener {@AutowiredRabbitTemplate 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 {@Autowiredpublic RabbitTemplate rabbitTemplate;@Testvoid testSimple() {String exchangName = "hmall.direct";rabbitTemplate.convertAndSend(exchangName, "yellow", "hello, w");}
}
消费者指定对列
@Component
@Slf4j
public class SpringAmqbListener {@AutowiredRabbitTemplate 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 {@Autowiredpublic RabbitTemplate rabbitTemplate;@Testvoid 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
@Beanpublic MessageConverter messageConverter() {return new Jackson2JsonMessageConverter();}