嘻哈飞车族腻害,高人都是这样玩SpringBoot整合RabbitMQ( 三 )


(1)配置 topic 模式
@Configurationpublic class RabbitTopicConfig {public static final String TOPICNAME = "yolo-topic";@BeanTopicExchange topicExchange() {return new TopicExchange(TOPICNAME, true, false);}@BeanQueue xiaomi() {return new Queue("xiaomi");}@BeanQueue huawei() {return new Queue("huawei");}@BeanQueue phone() {return new Queue("phone");}@BeanBinding xiaomiBinding() {//xiaomi.# 表示如果路由的 routingKey 是以xiaomi 开头就会发送到 xiaomi 这个队列上return BindingBuilder.bind(xiaomi()).to(topicExchange()).with("xiaomi.#");}@BeanBinding huaweiBinding() {//huawei.#return BindingBuilder.bind(huawei()).to(topicExchange()).with("huawei.#");}@BeanBinding phoneBinding() {// #.phone.# 表示routingKey 中包含 phone 就会被发送到 phone 这个队列上return BindingBuilder.bind(phone()).to(topicExchange()).with("#.phone.#");}}123456789101112131415161718192021222324252627282930313233343536373839404142(2) 消费者
@Componentpublic class TopicReceiver {@RabbitListener(queues = "xiaomi")public void handler1(String msg) {System.out.println("TopicReceiver:handler1:" + msg);}@RabbitListener(queues = "huawei")public void handler2(String msg) {System.out.println("TopicReceiver:handler2:" + msg);}@RabbitListener(queues = "phone")public void handler3(String msg) {System.out.println("TopicReceiver:handler3:" + msg);}}1234567891011121314151617(3)测试:生产者
@Testpublic void test2() {//可以被小米的队列收到rabbitTemplate.convertAndSend(RabbitTopicConfig.TOPICNAME, "xiaomi.news", "小米新闻");//可以被手机的队列收到rabbitTemplate.convertAndSend(RabbitTopicConfig.TOPICNAME, "vivo.phone", "vivo 手机");//可以被华为和手机的队列收到rabbitTemplate.convertAndSend(RabbitTopicConfig.TOPICNAME, "huawei.phone", "华为手机");}123456789这种模式使用的是 header 中的 key/value (键值对) 匹配队列 , 也和 routingKey 无关
(1)配置 config
@Configurationpublic class RabbitHeaderConfig {public static final String HEADERNAME = "yolo-header";@BeanHeadersExchange headersExchange() {return new HeadersExchange(HEADERNAME, true, false);}@BeanQueue queueName() {return new Queue("name-queue");}@BeanQueue queueAge() {return new Queue("age-queue");}@BeanBinding bindingName() {Map map = new HashMap<>();//map.put("name", "yolo");//whereAny 表示消息的header中只要有一个header匹配上map中的key,value,就把消息发送到对应的队列上return BindingBuilder.bind(queueName()).to(headersExchange()).whereAny(map).match();}@BeanBinding bindingAge() {//只要有 , age 这个字段 , 就发送到相应的队列上去return BindingBuilder.bind(queueAge()).to(headersExchange()).where("age").exists();}}1234567891011121314151617181920212223242526272829303132333435(2)消费者
@Componentpublic class HeaderReceiver {@RabbitListener(queues = "name-queue")public void handler1(byte[] msg) {System.out.println("HeaderReceiver:handler1:" + new String(msg, 0, msg.length));}@RabbitListener(queues = "age-queue")public void handler2(byte[] msg) {System.out.println("HeaderReceiver:handler2:" + new String(msg, 0, msg.length));}}123456789101112