MQ!Rabbit-client ChannelN

MQ!Rabbit-client ChannelN

MQ!Rabbit-client command中有一个小尾巴没有处理,看下面的代码

public void handleFrame(Frame frame) throws IOException {
    AMQCommand command = _command;
    if (command.handleFrame(frame)) { // a complete command has rolled off the assembly line
        _command = new AMQCommand(); // prepare for the next one
        handleCompleteInboundCommand(command);
    }
}

这段代码是rabbitmq处理帧的操作,当时分析了command.handleFrame(frame)这个方法实际上就是调用CommandAssembler.handleFrame()。这里我们来下面的方法handleCompleteInboundCommand(command);

// handle a command which has been assembled
// 处理已组装好的命令
public void handleCompleteInboundCommand(AMQCommand command) throws IOException {
        // First, offer the command to the asynchronous-command
        // handling mechanism, which gets to act as a filter on the
        // incoming command stream.  If processAsync() returns true,
        // the command has been dealt with by the filter and so should
        // not be processed further.  It will return true for
        // asynchronous commands (deliveries/returns/other events),
        // and false for commands that should be passed on to some
        // waiting RPC continuation.
        // 过滤掉已经处理的命令
        if (!processAsync(command)) {
            // The filter decided not to handle/consume the command,
            // so it must be a response to an earlier RPC.

            if (_checkRpcResponseType) {
                synchronized (_channelMutex) {
                    // check if this reply command is intended for the current waiting request before calling nextOutstandingRpc()
                    if (_activeRpc != null && !_activeRpc.canHandleReply(command)) {
                        // this reply command is not intended for the current waiting request
                        // most likely a previous request timed out and this command is the reply for that.
                        // Throw this reply command away so we don't stop the current request from waiting for its reply
                        return;
                    }
                }
            }
            final RpcWrapper nextOutstandingRpc = nextOutstandingRpc();
            // the outstanding RPC can be null when calling Channel#asyncRpc
            if(nextOutstandingRpc != null) {
                nextOutstandingRpc.complete(command);
                markRpcFinished();
            }
        }
    }

敲黑板了!!!🐷

processAsync这个方法的实现是在ChnnelN中(终于绕到ChannelN上了 😄)。

另外这个方法也是AMQChannel中唯一的抽象方法

ChannelN是整个RabbitMQ客户端最核心的一个类了✨

ChannelN的成员变量

private final Map<String, Consumer> _consumers = Collections.synchronizedMap(new HashMap<String, Consumer>());
private volatile Consumer defaultConsumer = null;
private final ConsumerDispatcher dispatcher;

private final Collection<ReturnListener> returnListeners = new CopyOnWriteArrayList<ReturnListener>();

private final Collection<FlowListener> flowListeners = new CopyOnWriteArrayList<FlowListener>();

private volatile CountDownLatch finishedShutdownFlag = null;

private final Collection<ConfirmListener> confirmListeners = new CopyOnWriteArrayList<ConfirmListener>();
private long nextPublishSeqNo = 0L;
private final SortedSet<Long> unconfirmedSet = Collections.synchronizedSortedSet(new TreeSet<Long>());
private volatile boolean onlyAcksReceived = true;

processAsync方法

原文注释都被我干掉了🙃

@Override public boolean processAsync(Command command) throws IOException
{
    Method method = command.getMethod();
    
    // 方法帧 Channel.Close,异步关闭
    if (method instanceof Channel.Close) {
        asyncShutdown(command);
        return true;
    }

    // 链接打开中
    if (isOpen()) {         
        if (method instanceof Basic.Deliver) {
           processDelivery(command, (Basic.Deliver) method);
           return true;
        } else if (method instanceof Basic.Return) {
           callReturnListeners(command, (Basic.Return) method);
           return true;
        } else if (method instanceof Channel.Flow) {
           Channel.Flow channelFlow = (Channel.Flow) method;
           synchronized (_channelMutex) {
               _blockContent = !channelFlow.getActive();
               transmit(new Channel.FlowOk(!_blockContent));
               _channelMutex.notifyAll();
           }
           return true;
        } else if (method instanceof Basic.Ack) {
           Basic.Ack ack = (Basic.Ack) method;
           callConfirmListeners(command, ack);
           handleAckNack(ack.getDeliveryTag(), ack.getMultiple(), false);
           return true;
        } else if (method instanceof Basic.Nack) {
            Basic.Nack nack = (Basic.Nack) method;
            callConfirmListeners(command, nack);
            handleAckNack(nack.getDeliveryTag(), nack.getMultiple(), true);
            return true;
         } else if (method instanceof Basic.RecoverOk) {
            for (Map.Entry<String, Consumer> entry : Utility.copy(_consumers).entrySet())               {
                 this.dispatcher.handleRecoverOk(entry.getValue(), entry.getKey());
               }
                
            return false;
         } else if (method instanceof Basic.Cancel) {
            Basic.Cancel m = (Basic.Cancel)method;
            String consumerTag = m.getConsumerTag();
            Consumer callback = _consumers.remove(consumerTag);
            if (callback == null) {
               callback = defaultConsumer;
            }
            if (callback != null) {
               try {
                    this.dispatcher.handleCancel(callback, consumerTag);
                } catch (Throwable ex) {
                      getConnection().getExceptionHandler().
                      handleConsumerException(this, ex,              callback,consumerTag,"handleCancel");
                 }
             }
             return true;
         } else {
            return false;
         }
    } else {
         // Channel.CloseOk方法
         if (method instanceof Channel.CloseOk) {                
                return false;
         } else {               
                return true;
         }
    }
 }

这个方法主要用来针对接受到brokerAMQCommand进行进一步的处理,至于怎么接受Socket,怎么封装成帧,怎么确定一个AMQComand已经封装完毕,都已在调用此方法前完成。此方法可以处理:Channel.Close, Basic.Deliver, Basic.Return, Channel.Flow, Basic.Ack, Basic.Nack,Basic.RecoverOk, Basic.Cancel, Channel.CloseOk等。

那来吧开始打怪了🤢。

// Basic.Deliver
processDelivery(command, (Basic.Deliver) method);

protected void processDelivery(Command command, Basic.Deliver method) {
      Basic.Deliver m = method;

      Consumer callback = _consumers.get(m.getConsumerTag());
      if (callback == null) {
          if (defaultConsumer == null) {
              // No handler set. We should blow up as this message
              // needs acking, just dropping it is not enough. See bug
              // 22587 for discussion.
              throw new IllegalStateException("Unsolicited delivery -" +
                      " see Channel.setDefaultConsumer to handle this" +
                      " case.");
          } else {
              callback = defaultConsumer;
          }
      }

      Envelope envelope = new Envelope(m.getDeliveryTag(),
                                       m.getRedelivered(),
                                       m.getExchange(),
                                       m.getRoutingKey());
      try {
          // call metricsCollector before the dispatching (which is async anyway)
          // this way, the message is inside the stats before it is handled
          // in case a manual ack in the callback, the stats will be able to record the ack
          metricsCollector.consumedMessage(this, m.getDeliveryTag(), m.getConsumerTag());
          // ConsumerWorkService实例
          this.dispatcher.handleDelivery(callback,
                                         m.getConsumerTag(),
                                         envelope,
                                         (BasicProperties) command.getContentHeader(),
                                         command.getContentBody());
      } catch (Throwable ex) {
          getConnection().getExceptionHandler().handleConsumerException(this,
              ex,
              callback,
              m.getConsumerTag(),
              "handleDelivery");
      }
}

在学习ConsumerWorkService里面留了一个尾巴就是ConsumerDispatcher。这里会进行补充吧。分析下上面代码里面的this.dispatcher.handleDelivery

public void handleDelivery(final Consumer delegate,
                           final String consumerTag,
                           final Envelope envelope,
                           final AMQP.BasicProperties properties,
                           final byte[] body) throws IOException {
    executeUnlessShuttingDown(
    new Runnable() {
        @Override
        public void run() {
            try {
                delegate.handleDelivery(consumerTag,
                        envelope,
                        properties,
                        body);
            } catch (Throwable ex) {
                connection.getExceptionHandler().handleConsumerException(
                        channel,
                        ex,
                        delegate,
                        consumerTag,
                        "handleDelivery");
            }
        }
    });
}

不要看里面Runnable的实现看外面套的那层方法:

private void executeUnlessShuttingDown(Runnable r) {
  if (!this.shuttingDown) execute(r);
}

private void execute(Runnable r) {
  checkShutdown();
  this.workService.addWork(this.channel, r);
}

这里就可以看到最后其实还是将需要处理的任务封装为一个Runnable然后调用了workService.addWork

所以说其实ConsumerDispatcher其实就是把任务分发给workPool处理。

什么?不知道workService.addWork是干什么的! 嘿嘿,去帮我刷下浏览量吧😜 MQ!Rabbit-client ConsumerWorkService

★☆★☆★☆★☆★☆★☆ ⊙◎○●”·. 可爱的分割线 .·“●○◎⊙ ★☆★☆★☆★☆★☆★☆

上面已经跑偏了,这里主要是要学习ChannelN的。来继续看下其他方法吧

Basic.Qos & basicQos

@Override
public void basicQos(int prefetchSize, int prefetchCount, boolean global)
throws IOException{
    exnWrappingRpc(new Basic.Qos(prefetchSize, prefetchCount, global));
}

// AMQImpl
public Qos(int prefetchSize, int prefetchCount, boolean global) {
    this.prefetchSize = prefetchSize;
    this.prefetchCount = prefetchCount;
    this.global = global;
}

好吧,这个源码我是看不出来有什么了,只好找网上的说法了。

消费者在开启ACK的情况下,对接受到的消息可以根据业务的需要异步对消息进行确认。
然而在实际使用过程中,由于消费者自身处理能力有限,从RabbitMQ获取一定数量的消息后,希望rabbitmq不再将队列中的消息推送过来,当对消息处理完后(即对消息进行了ack,并且有能力处理更多的消息)再接受来自队列的消息。在这种场景下,我们可以设置Basic.Qos中的prefetch_count来达到这个效果。

Basic.Consume & basicConsume

发送Basic.Consume帧,然后等待Basic.ConsumeOk帧。待收到broker端的Basic.ConsumeOk帧之后,触发BlockingRpcContinuation中的transformReply()方法

当发送Basic.Consume帧之后,由broker返回的是Basic.ConsumeOk帧+Basic.Deliver帧,Basic.ConsumerOk帧由下面方法处理,Basic.Deliver帧由processAsync处理。

@Override
public String basicConsume(String queue, final boolean autoAck, String consumerTag,
                           boolean noLocal, boolean exclusive, Map<String, Object>          arguments,
                           final Consumer callback)
    throws IOException {
    final Method m = new Basic.Consume.Builder()
        .queue(queue)
        .consumerTag(consumerTag)
        .noLocal(noLocal)
        .noAck(autoAck)
        .exclusive(exclusive)
        .arguments(arguments)
        .build();
    BlockingRpcContinuation<String> k = new BlockingRpcContinuation<String>(m) {
        @Override
        public String transformReply(AMQCommand replyCommand) {
            String actualConsumerTag = ((Basic.ConsumeOk) replyCommand.getMethod()).getConsumerTag();
            _consumers.put(actualConsumerTag, callback);

            // need to register consumer in stats before it actually starts consuming
            metricsCollector.basicConsume(ChannelN.this, actualConsumerTag, autoAck);

            dispatcher.handleConsumeOk(callback, actualConsumerTag);
            return actualConsumerTag;
        }
    };


    rpc(m, k);

    try {
        if(_rpcTimeout == NO_RPC_TIMEOUT) {
            return k.getReply();
        } else {
            try {
                return k.getReply(_rpcTimeout);
            } catch (TimeoutException e) {
                throw wrapTimeoutException(m, e);
            }
        }
    } catch(ShutdownSignalException ex) {
        throw wrap(ex);
    }
}

Basic.Get & basicGet

基本上就是客户端发送Basic.Get至Broker,Broker返回Basic.GetOK并携带数据。注意方法最后返回GetResponse对象,这个对象就是包装了一下数据。

public GetResponse basicGet(String queue, boolean autoAck)
    throws IOException
{
    AMQCommand replyCommand = exnWrappingRpc(new Basic.Get.Builder()
                                              .queue(queue)
                                              .noAck(autoAck)
                                             .build());
    Method method = replyCommand.getMethod();

    if (method instanceof Basic.GetOk) {
        Basic.GetOk getOk = (Basic.GetOk)method;
        Envelope envelope = new Envelope(getOk.getDeliveryTag(),
                                         getOk.getRedelivered(),
                                         getOk.getExchange(),
                                         getOk.getRoutingKey());
        BasicProperties props = (BasicProperties)replyCommand.getContentHeader();
        byte[] body = replyCommand.getContentBody();
        int messageCount = getOk.getMessageCount();
        return new GetResponse(envelope, props, body, messageCount);
    } else if (method instanceof Basic.GetEmpty) {
        return null;
    } else {
        throw new UnexpectedMethodError(method);
    }
}

事务

/** Public API - {@inheritDoc} */
public Tx.SelectOk txSelect()
    throws IOException
{
    return (Tx.SelectOk) exnWrappingRpc(new Tx.Select()).getMethod();
}

/** Public API - {@inheritDoc} */
public Tx.CommitOk txCommit()
    throws IOException
{
    return (Tx.CommitOk) exnWrappingRpc(new Tx.Commit()).getMethod();
}

/** Public API - {@inheritDoc} */
public Tx.RollbackOk txRollback()
    throws IOException
{
    return (Tx.RollbackOk) exnWrappingRpc(new Tx.Rollback()).getMethod();
}

上面几个方法参考博客:

https://blog.csdn.net/u013256816/article/details/70214863

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

推荐阅读更多精彩内容

  • 来源 RabbitMQ是用Erlang实现的一个高并发高可靠AMQP消息队列服务器。支持消息的持久化、事务、拥塞控...
    jiangmo阅读 10,359评论 2 34
  • 概述 本文介绍一下AMQP协议和RabbitMQ中几个比较重要的方法 AMQP 我们知道RabbitMQ是遵从AM...
    Tian_Peng阅读 2,083评论 0 1
  • % rabbitMQ learn% qijun% 19/01/2018 mq 的一些概念 mq: mq 是一个m...
    c7d122ec46c0阅读 2,074评论 0 21
  • RabbitMQ是采用Erlang语言实现AMQP(Advanced Message Queuing Protoc...
    陈晨_软件五千言阅读 2,053评论 0 5
  • 推荐指数: 6.0 书籍主旨关键词:特权、焦点、注意力、语言联想、情景联想 观点: 1.统计学现在叫数据分析,社会...
    Jenaral阅读 5,721评论 0 5