rabbitMQ - 4 - 代码使用4种Exchange

1 Fanout

1.1 新建一个fanout类型的exchange

这里的创建都是用代码来创建,也可以在后台界面操作。

@Bean
    FanoutExchange fanoutExchange() {
        return new FanoutExchange("zenghongFanoutExchange");
    }

启动服务后可以从控制台看到zenghongFanoutExchange已经创建成功:


image.png

1.2 再创建一个队列

   @Bean
    public Queue zenghongFanoutQueue() {
        return new Queue("zenghongFanoutQueue");
    }
image.png

1.3 绑定这个exchange和queue

    @Bean
    Binding bindingExchangeC(Queue zenghongFanoutQueue, FanoutExchange zenghongFanoutExchange) {
        return BindingBuilder.bind(zenghongFanoutQueue).to(zenghongFanoutExchange);
    }
image.png

1.4 生产者和消费者代码:

public void sendFanout(){
        String sendMsg = "my Fanout msg " + new Date();
        System.out.println("Sender1 : " + sendMsg);
        this.rabbitTemplate.convertAndSend("zenghongFanoutExchange",null,sendMsg);
    }

这里第二个参数是routing key ,我们传null。

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author: zenghong
 * @Date: 2019/4/25 09:46
 * @Description: TODO
 */
@Component
@RabbitListener(queues = "zenghongFanoutQueue")
public class FanoutCosumer {
    @RabbitHandler
    public void process(String msg) {
        System.out.println("FanoutCosumer Receiver1  : " + msg);
    }
}

1.5 测试接口

@RestController
@RequestMapping("/rabbit")
public class RabbitMqController {
    @Autowired
    private HelloSender helloSender1;

    @PostMapping("/hello")
    public String hello() {
        helloSender1.send();
        return "success";
    }

    @PostMapping("/myFanout")
    public String myFanout() {
        helloSender1.sendFanout();
        return "myFanout success";
    }

1.6 发送请求

image.png

image.png

消息被成功发送和接收,fanout果然是不需要routing key的。

2 direct

2.1 创建一个directExchange(zenghongDirectExchange) 和 两个 queue(zenghongDirectQueue1,zenghongDirectQueue2),然后绑定zenghongDirectExchange 和 zenghongDirectQueue1,绑定zenghongDirectExchange 和 zenghongDirectQueue2。

 @Bean
    DirectExchange zenghongDirectExchange() {
        return new DirectExchange("zenghongDirectExchange");
    }
    @Bean
    public Queue zenghongDirectQueue1() {
        return new Queue("zenghongDirectQueue1");
    }
    @Bean
    public Queue zenghongDirectQueue2() {
        return new Queue("zenghongDirectQueue2");
    }
     @Bean
    Binding bindingExchange2(Queue zenghongDirectQueue1, DirectExchange zenghongDirectExchange) {
        return BindingBuilder.bind(zenghongDirectQueue1).to(zenghongDirectExchange).with("direct queue1");
    }
    @Bean
    Binding bindingExchange3(Queue zenghongDirectQueue2, DirectExchange zenghongDirectExchange) {
        return BindingBuilder.bind(zenghongDirectQueue2).to(zenghongDirectExchange).with("direct queue2");
    }

2.2 编写sender、receiver和测试接口

sender:

public void sendDirect(){
        String sendMsg = "my Direct msg " + new Date();
        System.out.println("Sender : " + sendMsg);
        this.rabbitTemplate.convertAndSend("zenghongDirectExchange","direct queue1",sendMsg);
    }

注意:这里send发送的routing key和 queue1的binding key完全比配。
receiver:


@Component
@RabbitListener(queues = "zenghongDirectQueue1")
public class DirectCosumer1 {
    @RabbitHandler
    public void process(String msg) {
        System.out.println("DirectCosumer1 Receiver1  : " + msg);
    }
}
@Component
@RabbitListener(queues = "zenghongDirectQueue2")
public class DirectCosumer2 {
    @RabbitHandler
    public void process(String msg) {
        System.out.println("DirectCosumer2 Receiver1  : " + msg);
    }
}

接口:

  @PostMapping("/myDirect")
    public String myDirect() {
        helloSender1.sendDirect();
        return "myDirect success";
    }

2.3 测试验证:

image.png

控制台:


image.png

和我们预想的一样,监听queue1的DirectCosumer1接收到了消息。

3 topic

3.1 创建exchange、queue并绑定:

    @Bean
    TopicExchange zenghongTopicExchange() {
        return new TopicExchange("zenghongTopicExchange");
    }
    @Bean
    public Queue zenghongTopicQueue1() {
        return new Queue("zenghongTopicQueue1");
    }
    @Bean
    public Queue zenghongTopicQueue2() {
        return new Queue("zenghongTopicQueue2");
    }
    @Bean
    Binding bindingExchange2(Queue zenghongTopicQueue1, TopicExchange zenghongTopicExchange) {
        return BindingBuilder.bind(zenghongTopicQueue1).to(zenghongTopicExchange).with("queue1.#");
    }
    @Bean
    Binding bindingExchange3(Queue zenghongTopicQueue2, TopicExchange zenghongTopicExchange) {
        return BindingBuilder.bind(zenghongTopicQueue2).to(zenghongTopicExchange).with("queue1.*");
    }

3.2 sender 和 cosumer

    public void sendTopic(){
        String sendMsg = "my Topic msg " + new Date();
        System.out.println("Sender : " + sendMsg);
        this.rabbitTemplate.convertAndSend("zenghongTopicExchange","queue1.hahahaha",sendMsg);
    }

3.3 测试代码和测试

@PostMapping("/myTopic")
    public String myTopic() {
        helloSender1.sendTopic();
        return "myTopic success";
    }
image.png
image.png

和我们预想的一样,queue1.hahahaha(routing key ) 和 queue1.# 、 queue1.* 都匹配上了,所以两个队列的cosumer都收到了消息。

4 header

4.1 创建queue exchange 并绑定

    @Bean
    HeadersExchange zenghongHeadersExchange() {
        return new HeadersExchange("zenghongHeadersExchange");
    }
    @Bean
    public Queue zenghongHeadersQueue() {
        return new Queue("zenghongHeadersQueue");
    }
    @Bean
    Binding bindingExchange6(Queue zenghongHeadersQueue, HeadersExchange zenghongHeadersExchange) {
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("test1","test");
        return BindingBuilder.bind(zenghongHeadersQueue).to(zenghongHeadersExchange).whereAll(map).match();
    }

4.2 sender和cosumer

public void sendHeaders(){
        String sendMsg = "my Headers msg " + new Date();
        System.out.println("Sender : " + sendMsg);
        Message msg= null;
        try {
            msg = MessageBuilder.withBody(sendMsg.getBytes("utf-8")).
                    setHeader("test1","test").build();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        this.rabbitTemplate.convertAndSend("zenghongHeadersExchange",null,
                msg);
    }
@Component
@RabbitListener(queues = "zenghongHeadersQueue")
public class HeadersCosumer {
    @RabbitHandler
     public void process(Message message) {
        try {
            System.out.println("HeadersCosumer Receiver  : " + new String(message.getBody(),"utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

4.3 测试代码并测试

     @PostMapping("/myHeaders")
    public String myHeaders() {
        helloSender1.sendHeaders();
        return "myHeaders success";
    }
image.png

然后我们发现报错了,而且在刷屏!

org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Listener method 'no match' threw exception
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:198) ~[spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.onMessage(MessagingMessageListenerAdapter.java:127) ~[spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:1552) ~[spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.actualInvokeListener(AbstractMessageListenerContainer.java:1478) ~[spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:1466) ~[spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:1461) ~[spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:1410) ~[spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:870) [spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:854) [spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$1600(SimpleMessageListenerContainer.java:78) [spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.mainLoop(SimpleMessageListenerContainer.java:1137) [spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1043) [spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
Caused by: org.springframework.amqp.AmqpException: No method found for class [B
    at org.springframework.amqp.rabbit.listener.adapter.DelegatingInvocableHandler.getHandlerForPayload(DelegatingInvocableHandler.java:149) ~[spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.amqp.rabbit.listener.adapter.DelegatingInvocableHandler.invoke(DelegatingInvocableHandler.java:129) ~[spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.amqp.rabbit.listener.adapter.HandlerAdapter.invoke(HandlerAdapter.java:60) ~[spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:190) ~[spring-rabbit-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    ... 12 common frames omitted

为啥在刷屏呢?看看官方说的

If retries are not enabled and the listener throws an exception, by default the delivery will be retried indefinitely. You can modify this behavior in two ways; set the defaultRequeueRejected
property to false
and zero re-deliveries will be attempted; or, throw an AmqpRejectAndDontRequeueException
to signal the message should be rejected. This is the mechanism used when retries are enabled and the maximum delivery attempts are reached.

还好我们有百度翻译:

如果未启用重试,并且侦听器引发异常,则默认情况下将无限期重试传递。您可以通过两种方式修改此行为;设置默认的Requerejected
属性改为假
并且将尝试零次重新传递;或者,引发amqpReject和donTrequeueException
要发出信号,应拒绝该消息。这是启用重试并达到最大传递尝试次数时使用的机制。

知道为啥要刷屏了,为啥要报错呢? 查了一下,需要消费者把@RabbitListener放到方法上。

@Component
public class HeadersCosumer {

    @RabbitListener(queues = "zenghongHeadersQueue")
    @RabbitHandler
    public void process(Message message) {
        try {
            System.out.println("HeadersCosumer Receiver  : " + new String(message.getBody(),"utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
image.png

成功接收到了消息。

下一章 5 可靠性传输

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,012评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,628评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,653评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,485评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,574评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,590评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,596评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,340评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,794评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,102评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,276评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,940评论 5 339
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,583评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,201评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,441评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,173评论 2 366
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,136评论 2 352

推荐阅读更多精彩内容