主頁 > 後端開發 > 【RocketMQ】訊息的消費

【RocketMQ】訊息的消費

2022-07-26 08:17:17 後端開發

上一講【RocketMQ】訊息的拉取

訊息消費

當RocketMQ進行訊息消費的時候,是通過ConsumeMessageConcurrentlyServicesubmitConsumeRequest方法,將訊息提交到執行緒池中進行消費,具體的處理邏輯如下:

  1. 如果本次訊息的個數小于等于批量消費的大小consumeBatchSize,構建消費請求ConsumeRequest,直接提交到執行緒池中進行消費即可
  2. 如果本次訊息的個數大于批量消費的大小consumeBatchSize,說明需要分批進行提交,每次構建consumeBatchSize個訊息提交到執行緒池中進行消費
  3. 如果出現拒絕提交的例外,呼叫submitConsumeRequestLater方法延遲進行提交

RocketMQ訊息消費是批量進行的,如果一批訊息的個數小于預先設定的批量消費大小,直接構建消費請求將消費任務提交到執行緒池處理即可,否則需要分批進行提交,

public class ConsumeMessageConcurrentlyService implements ConsumeMessageService {
    @Override
    public void submitConsumeRequest(
        final List<MessageExt> msgs,
        final ProcessQueue processQueue,
        final MessageQueue messageQueue,
        final boolean dispatchToConsume) {
        final int consumeBatchSize = this.defaultMQPushConsumer.getConsumeMessageBatchMaxSize();
        // 如果訊息的個數小于等于批量消費的大小
        if (msgs.size() <= consumeBatchSize) {
            // 構建消費請求
            ConsumeRequest consumeRequest = new ConsumeRequest(msgs, processQueue, messageQueue);
            try {
                // 加入到消費執行緒池中
                this.consumeExecutor.submit(consumeRequest);
            } catch (RejectedExecutionException e) {
                this.submitConsumeRequestLater(consumeRequest);
            }
        } else {
            // 遍歷訊息
            for (int total = 0; total < msgs.size(); ) {
                // 創建訊息串列,大小為consumeBatchSize,用于批量提交使用
                List<MessageExt> msgThis = new ArrayList<MessageExt>(consumeBatchSize);
                for (int i = 0; i < consumeBatchSize; i++, total++) {
                    if (total < msgs.size()) {
                        // 加入到訊息串列中
                        msgThis.add(msgs.get(total));
                    } else {
                        break;
                    }
                }
                // 創建ConsumeRequest
                ConsumeRequest consumeRequest = new ConsumeRequest(msgThis, processQueue, messageQueue);
                try {
                    // 加入到消費執行緒池中
                    this.consumeExecutor.submit(consumeRequest);
                } catch (RejectedExecutionException e) {
                    for (; total < msgs.size(); total++) {
                        msgThis.add(msgs.get(total));
                    }
                    // 如果出現拒絕提交例外,延遲進行提交
                    this.submitConsumeRequestLater(consumeRequest);
                }
            }
        }
    }
}

消費任務運行

ConsumeRequestConsumeMessageConcurrentlyService的內部類,實作了Runnable介面,在run方法中,對消費任務進行了處理:

  1. 判斷訊息所屬的處理佇列processQueue是否處于洗掉狀態,如果已被洗掉,不進行處理

  2. 重置訊息的重試主題

    因為延遲訊息的主題在后續處理的時候被設定為SCHEDULE_TOPIC_XXXX,所以這里需要重置,

  3. 如果設定了訊息消費鉤子函式,執行executeHookBefore鉤子函式

  4. 獲取訊息監聽器,呼叫訊息監聽器的consumeMessage進行訊息消費,并回傳訊息的消費結果狀態,狀態有兩種分別為CONSUME_SUCCESSRECONSUME_LATER

    CONSUME_SUCCESS:表示訊息消費成功,

    RECONSUME_LATER:表示消費失敗,稍后延遲重新進行消費,

  5. 獲取消費的時長,判斷是否超時

  6. 如果設定了訊息消費鉤子函式,執行executeHookAfter鉤子函式

  7. 再次判斷訊息所屬的處理佇列是否處于洗掉狀態,如果不處于洗掉狀態,呼叫processConsumeResult方法處理消費結果

public class ConsumeMessageConcurrentlyService implements ConsumeMessageService {
    class ConsumeRequest implements Runnable {
        private final List<MessageExt> msgs;
        private final ProcessQueue processQueue; // 處理佇列
        private final MessageQueue messageQueue; // 訊息佇列
      
        @Override
        public void run() {
            // 如果處理佇列已被洗掉
            if (this.processQueue.isDropped()) {
                log.info("the message queue not be able to consume, because it's dropped. group={} {}", ConsumeMessageConcurrentlyService.this.consumerGroup, this.messageQueue);
                return;
            }
            // 獲取訊息監聽器
            MessageListenerConcurrently listener = ConsumeMessageConcurrentlyService.this.messageListener;
            ConsumeConcurrentlyContext context = new ConsumeConcurrentlyContext(messageQueue);
            ConsumeConcurrentlyStatus status = null;
            // 重置訊息重試主題名稱 
            defaultMQPushConsumerImpl.resetRetryAndNamespace(msgs, defaultMQPushConsumer.getConsumerGroup());
            ConsumeMessageContext consumeMessageContext = null;
            // 如果設定了鉤子函式
            if (ConsumeMessageConcurrentlyService.this.defaultMQPushConsumerImpl.hasHook()) {
                // ...
// 執行鉤子函式            
              ConsumeMessageConcurrentlyService.this.defaultMQPushConsumerImpl.executeHookBefore(consumeMessageContext);
            }

            long beginTimestamp = System.currentTimeMillis();
            boolean hasException = false;
            ConsumeReturnType returnType = ConsumeReturnType.SUCCESS;
            try {
                if (msgs != null && !msgs.isEmpty()) {
                    for (MessageExt msg : msgs) {
                        // 設定消費開始時間戳
                        MessageAccessor.setConsumeStartTimeStamp(msg, String.valueOf(System.currentTimeMillis()));
                    }
                }
                // 通過訊息監聽器的consumeMessage進行訊息消費,并回傳消費結果狀態
                status = listener.consumeMessage(Collections.unmodifiableList(msgs), context);
            } catch (Throwable e) {
                log.warn(String.format("consumeMessage exception: %s Group: %s Msgs: %s MQ: %s",
                    RemotingHelper.exceptionSimpleDesc(e),
                    ConsumeMessageConcurrentlyService.this.consumerGroup,
                    msgs,
                    messageQueue), e);
                hasException = true;
            }
            // 計算消費時長
            long consumeRT = System.currentTimeMillis() - beginTimestamp;
            if (null == status) {
                if (hasException) {
                    // 出現例外
                    returnType = ConsumeReturnType.EXCEPTION;
                } else {
                    // 回傳NULL
                    returnType = ConsumeReturnType.RETURNNULL;
                }
            } else if (consumeRT >= defaultMQPushConsumer.getConsumeTimeout() * 60 * 1000) { // 判斷超時
                returnType = ConsumeReturnType.TIME_OUT; // 回傳型別置為超時
            } else if (ConsumeConcurrentlyStatus.RECONSUME_LATER == status) { // 如果延遲消費
                returnType = ConsumeReturnType.FAILED; // 回傳類置為失敗
            } else if (ConsumeConcurrentlyStatus.CONSUME_SUCCESS == status) { // 如果成功狀態
                returnType = ConsumeReturnType.SUCCESS; // 回傳型別為成功
            }
            // ...
            // 如果消費狀態為空
            if (null == status) {
                log.warn("consumeMessage return null, Group: {} Msgs: {} MQ: {}",
                    ConsumeMessageConcurrentlyService.this.consumerGroup,
                    msgs,
                    messageQueue);
                // 狀態置為延遲消費
                status = ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
            // 如果設定了鉤子函式
            if (ConsumeMessageConcurrentlyService.this.defaultMQPushConsumerImpl.hasHook()) {
                consumeMessageContext.setStatus(status.toString());
                consumeMessageContext.setSuccess(ConsumeConcurrentlyStatus.CONSUME_SUCCESS == status);
                // 執行executeHookAfter方法
                ConsumeMessageConcurrentlyService.this.defaultMQPushConsumerImpl.executeHookAfter(consumeMessageContext);
            }
            ConsumeMessageConcurrentlyService.this.getConsumerStatsManager()
                .incConsumeRT(ConsumeMessageConcurrentlyService.this.consumerGroup, messageQueue.getTopic(), consumeRT);
            if (!processQueue.isDropped()) {
                // 處理消費結果
                ConsumeMessageConcurrentlyService.this.processConsumeResult(status, context, this);
            } else {
                log.warn("processQueue is dropped without process consume result. messageQueue={}, msgs={}", messageQueue, msgs);
            }
        }
    }
}

// 重置訊息重試主題
public class DefaultMQPushConsumerImpl implements MQConsumerInner {
   public void resetRetryAndNamespace(final List<MessageExt> msgs, String consumerGroup) {
        // 獲取消費組的重試主題:%RETRY% + 消費組名稱
        final String groupTopic = MixAll.getRetryTopic(consumerGroup);
        for (MessageExt msg : msgs) {
            // 獲取訊息的重試主題名稱
            String retryTopic = msg.getProperty(MessageConst.PROPERTY_RETRY_TOPIC);
            // 如果重試主題不為空并且與消費組的重試主題一致
            if (retryTopic != null && groupTopic.equals(msg.getTopic())) {
                // 設定重試主題
                msg.setTopic(retryTopic);
            }
            if (StringUtils.isNotEmpty(this.defaultMQPushConsumer.getNamespace())) {
                msg.setTopic(NamespaceUtil.withoutNamespace(msg.getTopic(), this.defaultMQPushConsumer.getNamespace()));
            }
        }
    }
  
}

// 消費結果狀態
public enum ConsumeConcurrentlyStatus {
    /**
     * 消費成功
     */
    CONSUME_SUCCESS,
    /**
     * 消費失敗,延遲進行消費
     */
    RECONSUME_LATER;
}

處理消費結果

一、設定ackIndex

ackIndex的值用來判斷失敗訊息的個數,在processConsumeResult方法中根據消費結果狀態進行判斷,對ackIndex的值進行設定,前面可知消費結果狀態有以下兩種:

  • CONSUME_SUCCESS:訊息消費成功,此時ackIndex設定為訊息大小 - 1,表示訊息都消費成功,
  • RECONSUME_LATER:訊息消費失敗,回傳延遲消費狀態,此時ackIndex置為-1,表示訊息都消費失敗,

二、處理消費失敗的訊息

廣播模式

廣播模式下,如果訊息消費失敗,只將失敗的訊息列印出來不做其他處理,

集群模式

開啟for回圈,初始值為i = ackIndex + 1,結束條件為i < consumeRequest.getMsgs().size(),上面可知ackIndex有兩種情況:

  • 消費成功:ackIndex值為訊息大小-1,此時ackIndex + 1的值等于訊息的個數大小,不滿足for回圈的執行條件,相當于訊息都消費成功,不需要進行失敗的訊息處理,
  • 延遲消費:ackIndex值為-1,此時ackIndex+1為0,滿足for回圈的執行條件,從第一條訊息開始遍歷到最后一條訊息,呼叫sendMessageBack方法向Broker發送CONSUMER_SEND_MSG_BACK訊息,如果發送成功Broker會根據延遲等級,放入不同的延遲佇列中,到達延遲時間后,消費者將會重新進行拉取,如果發送失敗,加入到失敗訊息串列中,稍后重新提交消費任務進行處理,

三、移除訊息,更新拉取偏移量

以上步驟處理完畢后,首先呼叫removeMessage從處理佇列中移除訊息并回傳拉取訊息的偏移量,然后呼叫updateOffset更新拉取偏移量,

public class ConsumeMessageConcurrentlyService implements ConsumeMessageService {
    public void processConsumeResult(
        final ConsumeConcurrentlyStatus status,
        final ConsumeConcurrentlyContext context,
        final ConsumeRequest consumeRequest
    ) {
        // 獲取ackIndex
        int ackIndex = context.getAckIndex();
        if (consumeRequest.getMsgs().isEmpty())
            return;

        switch (status) {
            case CONSUME_SUCCESS: // 如果消費成功
                // 如果ackIndex大于等于訊息的大小
                if (ackIndex >= consumeRequest.getMsgs().size()) {
                    // 設定為訊息大小-1
                    ackIndex = consumeRequest.getMsgs().size() - 1;
                }
                // 計算消費成功的的個數
                int ok = ackIndex + 1;
                // 計算消費失敗的個數
                int failed = consumeRequest.getMsgs().size() - ok;
                this.getConsumerStatsManager().incConsumeOKTPS(consumerGroup, consumeRequest.getMessageQueue().getTopic(), ok);
                this.getConsumerStatsManager().incConsumeFailedTPS(consumerGroup, consumeRequest.getMessageQueue().getTopic(), failed);
                break;
            case RECONSUME_LATER: // 如果延遲消費
                // ackIndex置為-1
                ackIndex = -1;
                this.getConsumerStatsManager().incConsumeFailedTPS(consumerGroup, consumeRequest.getMessageQueue().getTopic(),
                    consumeRequest.getMsgs().size());
                break;
            default:
                break;
        }
        // 判斷消費模式
        switch (this.defaultMQPushConsumer.getMessageModel()) {
            case BROADCASTING: // 廣播模式
                for (int i = ackIndex + 1; i < consumeRequest.getMsgs().size(); i++) {
                    MessageExt msg = consumeRequest.getMsgs().get(i);
                    log.warn("BROADCASTING, the message consume failed, drop it, {}", msg.toString());
                }
                break;
            case CLUSTERING: // 集群模式
                List<MessageExt> msgBackFailed = new ArrayList<MessageExt>(consumeRequest.getMsgs().size());
                // 遍歷消費失敗的訊息
                for (int i = ackIndex + 1; i < consumeRequest.getMsgs().size(); i++) {
                    // 獲取訊息
                    MessageExt msg = consumeRequest.getMsgs().get(i);
                    // 向Broker發送延遲訊息
                    boolean result = this.sendMessageBack(msg, context);
                    // 如果發送失敗
                    if (!result) {
                        // 消費次數+1
                        msg.setReconsumeTimes(msg.getReconsumeTimes() + 1);
                        // 加入失敗訊息串列中
                        msgBackFailed.add(msg);
                    }
                }
                // 如果不為空
                if (!msgBackFailed.isEmpty()) {
                    consumeRequest.getMsgs().removeAll(msgBackFailed);
                    // 稍后重新進行消費
                    this.submitConsumeRequestLater(msgBackFailed, consumeRequest.getProcessQueue(), consumeRequest.getMessageQueue());
                }
                break;
            default:
                break;
        }
        // 從處理佇列中移除訊息
        long offset = consumeRequest.getProcessQueue().removeMessage(consumeRequest.getMsgs());
        if (offset >= 0 && !consumeRequest.getProcessQueue().isDropped()) {
            // 更新拉取偏移量
            this.defaultMQPushConsumerImpl.getOffsetStore().updateOffset(consumeRequest.getMessageQueue(), offset, true);
        }
    }
}

發送CONSUMER_SEND_MSG_BACK訊息

延遲級別

RocketMQ的延遲級別對應的延遲時間常量定義在MessageStoreConfigmessageDelayLevel變數中:

public class MessageStoreConfig {
    private String messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";
}

延遲級別與延遲時間對應關系:

延遲級別0 ---> 對應延遲時間1s,也就是延遲1秒后消費者重新從Broker拉取進行消費

延遲級別1 ---> 延遲時間5s

延遲級別2 ---> 延遲時間10s

...

以此類推,最大的延遲時間為2h

sendMessageBack方法中,首先從背景關系中獲取了延遲級別(ConsumeConcurrentlyContext中可以看到,延遲級別默認為0),并對主題加上Namespace,然后呼叫defaultMQPushConsumerImplsendMessageBack發送訊息:

public class ConsumeMessageConcurrentlyService implements ConsumeMessageService {
   public boolean sendMessageBack(final MessageExt msg, final ConsumeConcurrentlyContext context) {
        // 獲取延遲級別
        int delayLevel = context.getDelayLevelWhenNextConsume();
        // 對主題添加上Namespace
        msg.setTopic(this.defaultMQPushConsumer.withNamespace(msg.getTopic()));
        try {
            // 向Broker發送訊息
            this.defaultMQPushConsumerImpl.sendMessageBack(msg, delayLevel, context.getMessageQueue().getBrokerName());
            return true;
        } catch (Exception e) {
            log.error("sendMessageBack exception, group: " + this.consumerGroup + " msg: " + msg.toString(), e);
        }
        return false;
    }
}

// 并發消費背景關系
public class ConsumeConcurrentlyContext {
    /**
     * -1,不進行重試,加入DLQ佇列
     * 0, Broker控制重試頻率
     * >0, 客戶端控制
     */
    private int delayLevelWhenNextConsume = 0; // 默認為0
}

DefaultMQPushConsumerImpsendMessageBack方法中又呼叫了MQClientAPIImplconsumerSendMessageBack方法進行發送:

public class DefaultMQPushConsumerImpl implements MQConsumerInner {
    public void sendMessageBack(MessageExt msg, int delayLevel, final String brokerName)
        throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
        try {
            // 獲取Broker地址
            String brokerAddr = (null != brokerName) ? this.mQClientFactory.findBrokerAddressInPublish(brokerName)
                : RemotingHelper.parseSocketAddressAddr(msg.getStoreHost());
            // 呼叫consumerSendMessageBack方法發送訊息
            this.mQClientFactory.getMQClientAPIImpl().consumerSendMessageBack(brokerAddr, msg,
                this.defaultMQPushConsumer.getConsumerGroup(), delayLevel, 5000, getMaxReconsumeTimes());
        } catch (Exception e) {
            // ...
        } finally {
            msg.setTopic(NamespaceUtil.withoutNamespace(msg.getTopic(), this.defaultMQPushConsumer.getNamespace()));
        }
    }
}

MQClientAPIImplconsumerSendMessageBack方法中,可以看到設定的請求型別是CONSUMER_SEND_MSG_BACK,然后設定了訊息的相關資訊,向Broker發送請求:

public class MQClientAPIImpl {
    public void consumerSendMessageBack(
        final String addr,
        final MessageExt msg,
        final String consumerGroup,
        final int delayLevel,
        final long timeoutMillis,
        final int maxConsumeRetryTimes
    ) throws RemotingException, MQBrokerException, InterruptedException {
        // 創建請求頭
        ConsumerSendMsgBackRequestHeader requestHeader = new ConsumerSendMsgBackRequestHeader();
        // 設定請求型別為CONSUMER_SEND_MSG_BACK
        RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CONSUMER_SEND_MSG_BACK, requestHeader);
        // 設定消費組
        requestHeader.setGroup(consumerGroup);
        requestHeader.setOriginTopic(msg.getTopic());
        // 設定訊息物理偏移量
        requestHeader.setOffset(msg.getCommitLogOffset());
        // 設定延遲級別
        requestHeader.setDelayLevel(delayLevel);
        // 設定訊息ID
        requestHeader.setOriginMsgId(msg.getMsgId());
        // 設定最大消費次數
        requestHeader.setMaxReconsumeTimes(maxConsumeRetryTimes);
        // 向Broker發送請求
        RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
            request, timeoutMillis);
        assert response != null;
        switch (response.getCode()) {
            case ResponseCode.SUCCESS: {
                return;
            }
            default:
                break;
        }
        throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
    }
}

Broker對請求的處理

Broker對CONSUMER_SEND_MSG_BACK型別的請求在SendMessageProcessor中,處理邏輯如下:

  1. 根據消費組獲取訂閱資訊配置,如果獲取為空,記錄錯誤資訊,直接回傳
  2. 獲取消費組的重試主題,然后從重試佇列中隨機選取一個佇列,并創建TopicConfig主題配置資訊
  3. 根據訊息的物理偏移量從commitlog中獲取訊息
  4. 判斷訊息的消費次數是否大于等于最大消費次數 或者 延遲等級小于0
    • 如果條件滿足,表示需要把訊息放入到死信佇列DLQ中,此時設定DLQ佇列ID
    • 如果不滿足,判斷延遲級別是否為0,如果為0,使用3 + 訊息的消費次數作為新的延遲級別
  5. 新建訊息MessageExtBrokerInner,設定訊息的相關資訊,此時相當于生成了一個全新的訊息(會設定之前訊息的ID),會重新添加到CommitLog中,訊息主題的設定有兩種情況:
    • 達到了加入DLQ佇列的條件,此時主題為DLQ主題(%DLQ% + 消費組名稱),訊息之后會添加到選取的DLQ佇列中
    • 未達到DLQ佇列的條件,此時主題為重試主題(%RETRY% + 消費組名稱),之后重新進行消費
  6. 呼叫asyncPutMessage添加訊息,詳細程序可參考之前的文章【訊息的存盤】
public class SendMessageProcessor extends AbstractSendMessageProcessor implements NettyRequestProcessor {
    // 處理請求
    public CompletableFuture<RemotingCommand> asyncProcessRequest(ChannelHandlerContext ctx,
                                                                  RemotingCommand request) throws RemotingCommandException {
        final SendMessageContext mqtraceContext;
        switch (request.getCode()) {
            case RequestCode.CONSUMER_SEND_MSG_BACK:
                // 處理請求
                return this.asyncConsumerSendMsgBack(ctx, request);
            default:
                // ...
        }
    }
  
    private CompletableFuture<RemotingCommand> asyncConsumerSendMsgBack(ChannelHandlerContext ctx,
                                                                        RemotingCommand request) throws RemotingCommandException {
        final RemotingCommand response = RemotingCommand.createResponseCommand(null);
        final ConsumerSendMsgBackRequestHeader requestHeader =
                (ConsumerSendMsgBackRequestHeader)request.decodeCommandCustomHeader(ConsumerSendMsgBackRequestHeader.class);
        // ...
        // 根據消費組獲取訂閱資訊配置
        SubscriptionGroupConfig subscriptionGroupConfig =
            this.brokerController.getSubscriptionGroupManager().findSubscriptionGroupConfig(requestHeader.getGroup());
        // 如果為空,直接回傳
        if (null == subscriptionGroupConfig) {
            response.setCode(ResponseCode.SUBSCRIPTION_GROUP_NOT_EXIST);
            response.setRemark("subscription group not exist, " + requestHeader.getGroup() + " "
                + FAQUrl.suggestTodo(FAQUrl.SUBSCRIPTION_GROUP_NOT_EXIST));
            return CompletableFuture.completedFuture(response);
        }
        // ...
    
        // 獲取消費組的重試主題
        String newTopic = MixAll.getRetryTopic(requestHeader.getGroup());
        // 從重試佇列中隨機選取一個佇列
        int queueIdInt = ThreadLocalRandom.current().nextInt(99999999) % subscriptionGroupConfig.getRetryQueueNums();
        int topicSysFlag = 0;
        if (requestHeader.isUnitMode()) {
            topicSysFlag = TopicSysFlag.buildSysFlag(false, true);
        }
        // 創建TopicConfig主題配置資訊
        TopicConfig topicConfig = this.brokerController.getTopicConfigManager().createTopicInSendMessageBackMethod(
            newTopic,
            subscriptionGroupConfig.getRetryQueueNums(),
            PermName.PERM_WRITE | PermName.PERM_READ, topicSysFlag);
        //...
    
        // 根據訊息物理偏移量從commitLog檔案中獲取訊息
        MessageExt msgExt = this.brokerController.getMessageStore().lookMessageByOffset(requestHeader.getOffset());
        if (null == msgExt) {
            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("look message by offset failed, " + requestHeader.getOffset());
            return CompletableFuture.completedFuture(response);
        }
        // 獲取訊息的重試主題
        final String retryTopic = msgExt.getProperty(MessageConst.PROPERTY_RETRY_TOPIC);
        if (null == retryTopic) {
            MessageAccessor.putProperty(msgExt, MessageConst.PROPERTY_RETRY_TOPIC, msgExt.getTopic());
        }
        msgExt.setWaitStoreMsgOK(false);
        // 延遲等級獲取
        int delayLevel = requestHeader.getDelayLevel();
        // 獲取最大消費重試次數
        int maxReconsumeTimes = subscriptionGroupConfig.getRetryMaxTimes();
        if (request.getVersion() >= MQVersion.Version.V3_4_9.ordinal()) {
            Integer times = requestHeader.getMaxReconsumeTimes();
            if (times != null) {
                maxReconsumeTimes = times;
            }
        }
        // 判斷訊息的消費次數是否大于等于最大消費次數 或者 延遲等級小于0
        if (msgExt.getReconsumeTimes() >= maxReconsumeTimes
            || delayLevel < 0) {
            // 獲取DLQ主題
            newTopic = MixAll.getDLQTopic(requestHeader.getGroup());
            // 選取一個佇列
            queueIdInt = ThreadLocalRandom.current().nextInt(99999999) % DLQ_NUMS_PER_GROUP;
            // 創建DLQ的topicConfig
            topicConfig = this.brokerController.getTopicConfigManager().createTopicInSendMessageBackMethod(newTopic,
                    DLQ_NUMS_PER_GROUP,
                    PermName.PERM_WRITE | PermName.PERM_READ, 0);
            // ...
        } else {
             // 如果延遲級別為0
            if (0 == delayLevel) {
                // 更新延遲級別
                delayLevel = 3 + msgExt.getReconsumeTimes();
            }
            // 設定延遲級別
            msgExt.setDelayTimeLevel(delayLevel);
        }
        // 新建訊息
        MessageExtBrokerInner msgInner = new MessageExtBrokerInner();
        msgInner.setTopic(newTopic); // 設定主題
        msgInner.setBody(msgExt.getBody()); // 設定訊息
        msgInner.setFlag(msgExt.getFlag());
        MessageAccessor.setProperties(msgInner, msgExt.getProperties()); // 設定訊息屬性
        msgInner.setPropertiesString(MessageDecoder.messageProperties2String(msgExt.getProperties()));
        msgInner.setTagsCode(MessageExtBrokerInner.tagsString2tagsCode(null, msgExt.getTags()));
        msgInner.setQueueId(queueIdInt); // 設定佇列ID
        msgInner.setSysFlag(msgExt.getSysFlag());
        msgInner.setBornTimestamp(msgExt.getBornTimestamp());
        msgInner.setBornHost(msgExt.getBornHost());
        msgInner.setStoreHost(msgExt.getStoreHost()); 
        msgInner.setReconsumeTimes(msgExt.getReconsumeTimes() + 1);// 設定消費次數
        // 原始的訊息ID
        String originMsgId = MessageAccessor.getOriginMessageId(msgExt);
        // 設定訊息ID
        MessageAccessor.setOriginMessageId(msgInner, UtilAll.isBlank(originMsgId) ? msgExt.getMsgId() : originMsgId);
        msgInner.setPropertiesString(MessageDecoder.messageProperties2String(msgExt.getProperties()));
        // 添加重試訊息
        CompletableFuture<PutMessageResult> putMessageResult = this.brokerController.getMessageStore().asyncPutMessage(msgInner);
        return putMessageResult.thenApply((r) -> {
            if (r != null) {
                switch (r.getPutMessageStatus()) {
                    case PUT_OK:
                        // ...
                        return response;
                    default:
                        break;
                }
                response.setCode(ResponseCode.SYSTEM_ERROR);
                response.setRemark(r.getPutMessageStatus().name());
                return response;
            }
            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("putMessageResult is null");
            return response;
        });
    }
}

延遲訊息處理

由【訊息的存盤】文章可知,訊息添加會進入到asyncPutMessage方法中,首先獲取了事務型別,如果未使用事務或者是提交事務的情況下,對延遲時間級別進行判斷,如果延遲時間級別大于0,說明訊息需要延遲消費,此時做如下處理:

  1. 判斷訊息的延遲級別是否超過了最大延遲級別,如果超過了就使用最大延遲級別

  2. 獲取RMQ_SYS_SCHEDULE_TOPIC,它是在TopicValidator中定義的常量,值為SCHEDULE_TOPIC_XXXX:

    public class TopicValidator {
        // ...
        public static final String RMQ_SYS_SCHEDULE_TOPIC = "SCHEDULE_TOPIC_XXXX";
    }
    
  3. 根據延遲級別選取對應的佇列,一般會把相同延遲級別的訊息放在同一個佇列中

  4. 備份之前的TOPIC和佇列ID

  5. 更改訊息佇列的主題為RMQ_SYS_SCHEDULE_TOPIC,所以延遲訊息的主題最終被設定為RMQ_SYS_SCHEDULE_TOPIC,放在對應的延遲佇列中進行處理

public class CommitLog {
    public CompletableFuture<PutMessageResult> asyncPutMessage(final MessageExtBrokerInner msg) {
        // ...
        // 獲取事務型別
        final int tranType = MessageSysFlag.getTransactionValue(msg.getSysFlag());
        // 如果未使用事務或者提交事務
        if (tranType == MessageSysFlag.TRANSACTION_NOT_TYPE
                || tranType == MessageSysFlag.TRANSACTION_COMMIT_TYPE) {
            // 判斷延遲級別
            if (msg.getDelayTimeLevel() > 0) {
                // 如果超過了最大延遲級別
                if (msg.getDelayTimeLevel() > this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel()) {
                    msg.setDelayTimeLevel(this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel());
                }
                // 獲取RMQ_SYS_SCHEDULE_TOPIC
                topic = TopicValidator.RMQ_SYS_SCHEDULE_TOPIC;
                // 根據延遲級別選取對應的佇列
                int queueId = ScheduleMessageService.delayLevel2QueueId(msg.getDelayTimeLevel());

                // 備份之前的TOPIC和佇列ID
                MessageAccessor.putProperty(msg, MessageConst.PROPERTY_REAL_TOPIC, msg.getTopic());
                MessageAccessor.putProperty(msg, MessageConst.PROPERTY_REAL_QUEUE_ID, String.valueOf(msg.getQueueId()));
                msg.setPropertiesString(MessageDecoder.messageProperties2String(msg.getProperties()));
                // 設定SCHEDULE_TOPIC
                msg.setTopic(topic);
                msg.setQueueId(queueId);
            }
        }
        // ...
    }
}

拉取進度持久化

RocketMQ消費模式分為廣播模式和集群模式,廣播模式下消費進度保存在每個消費者端,集群模式下消費進度保存在Broker端,

廣播模式

更新進度

LocalFileOffsetStore中使用了一個ConcurrentMap型別的變數offsetTable存盤訊息佇列對應的拉取偏移量,KEY為訊息佇列,value為該訊息佇列對應的拉取偏移量,

在更新拉取進度的時候,從offsetTable中獲取當前訊息佇列的拉取偏移量,如果為空,則新建并保存到offsetTable中,否則獲取之前已經保存的偏移量,對值進行更新,需要注意這里只是更新了offsetTable中的資料,并沒有持久化到磁盤,持久化的操作在persistAll方法中

public class LocalFileOffsetStore implements OffsetStore {
    // offsetTable:KEY為訊息佇列,value為該訊息佇列的拉取偏移量
    private ConcurrentMap<MessageQueue, AtomicLong> offsetTable =
        new ConcurrentHashMap<MessageQueue, AtomicLong>();
  
    @Override
    public void updateOffset(MessageQueue mq, long offset, boolean increaseOnly) {
        if (mq != null) {
            // 獲取之前的拉取進度
            AtomicLong offsetOld = this.offsetTable.get(mq);
            if (null == offsetOld) {
                // 如果之前不存在,進行創建
                offsetOld = this.offsetTable.putIfAbsent(mq, new AtomicLong(offset));
            }
            // 如果不為空
            if (null != offsetOld) {
                if (increaseOnly) {
                    MixAll.compareAndIncreaseOnly(offsetOld, offset);
                } else {
                    // 更新拉取偏移量
                    offsetOld.set(offset);
                }
            }
        }
    }
}

加載進度

由于廣播模式下消費進度保存在消費者端,所以需要從本地磁盤加載之前保存的消費進度檔案,

LOCAL_OFFSET_STORE_DIR:消費進度檔案所在的根路徑

public final static String LOCAL_OFFSET_STORE_DIR = System.getProperty(
        "rocketmq.client.localOffsetStoreDir", System.getProperty("user.home") + File.separator + ".rocketmq_offsets");

在LocalFileOffsetStore的建構式中可以看到,對拉取偏移量的保存檔案路徑進行了設定,為LOCAL_OFFSET_STORE_DIR + 客戶端ID + 消費組名稱 + offsets.json,從名字上看,消費進度的資料格式是以JSON的形式進行保存的:

this.storePath = LOCAL_OFFSET_STORE_DIR + File.separator + this.mQClientFactory.getClientId() + File.separator +
            this.groupName + File.separator + "offsets.json";

在load方法中,首先從本地讀取 offsets.json檔案,并序列化為OffsetSerializeWrapper物件,然后將保存的消費進度加入到offsetTable中:

 public class LocalFileOffsetStore implements OffsetStore {
   
    // 檔案路徑
    public final static String LOCAL_OFFSET_STORE_DIR = System.getProperty(
        "rocketmq.client.localOffsetStoreDir",
        System.getProperty("user.home") + File.separator + ".rocketmq_offsets");
    private final String storePath;
    // ...
   
    public LocalFileOffsetStore(MQClientInstance mQClientFactory, String groupName) {
        this.mQClientFactory = mQClientFactory;
        this.groupName = groupName;
        // 設定拉取進度檔案的路徑
        this.storePath = LOCAL_OFFSET_STORE_DIR + File.separator +
            this.mQClientFactory.getClientId() + File.separator +
            this.groupName + File.separator +
            "offsets.json";
    }
    @Override
    public void load() throws MQClientException {
        // 從本地讀取拉取偏移量
        OffsetSerializeWrapper offsetSerializeWrapper = this.readLocalOffset();
        if (offsetSerializeWrapper != null && offsetSerializeWrapper.getOffsetTable() != null) {
            // 加入到offsetTable中
            offsetTable.putAll(offsetSerializeWrapper.getOffsetTable());

            for (Entry<MessageQueue, AtomicLong> mqEntry : offsetSerializeWrapper.getOffsetTable().entrySet()) {
                AtomicLong offset = mqEntry.getValue();
                log.info("load consumer's offset, {} {} {}",
                        this.groupName,
                        mqEntry.getKey(),
                        offset.get());
            }
        }
    }
  
    // 從本地加載檔案
    private OffsetSerializeWrapper readLocalOffset() throws MQClientException {
        String content = null;
        try {
            // 讀取檔案
            content = MixAll.file2String(this.storePath);
        } catch (IOException e) {
            log.warn("Load local offset store file exception", e);
        }
        if (null == content || content.length() == 0) {
            return this.readLocalOffsetBak();
        } else {
            OffsetSerializeWrapper offsetSerializeWrapper = null;
            try {
                // 序列化
                offsetSerializeWrapper =
                    OffsetSerializeWrapper.fromJson(content, OffsetSerializeWrapper.class);
            } catch (Exception e) {
                log.warn("readLocalOffset Exception, and try to correct", e);
                return this.readLocalOffsetBak();
            }

            return offsetSerializeWrapper;
        }
    }
}

OffsetSerializeWrapper

OffsetSerializeWrapper中同樣使用了ConcurrentMap,從磁盤的offsets.json檔案中讀取資料后,將JSON轉為OffsetSerializeWrapper物件,就可以通過OffsetSerializeWrapperoffsetTable獲取到之前保存的每個訊息佇列的消費進度,然后加入到LocalFileOffsetStoreoffsetTable中:

public class OffsetSerializeWrapper extends RemotingSerializable {
    private ConcurrentMap<MessageQueue, AtomicLong> offsetTable =
        new ConcurrentHashMap<MessageQueue, AtomicLong>();

    public ConcurrentMap<MessageQueue, AtomicLong> getOffsetTable() {
        return offsetTable;
    }

    public void setOffsetTable(ConcurrentMap<MessageQueue, AtomicLong> offsetTable) {
        this.offsetTable = offsetTable;
    }
}

持久化進度

updateOffset更新只是將記憶體中的資料進行了更改,并未保存到磁盤中,持久化的操作是在persistAll方法中實作的:

  1. 創建OffsetSerializeWrapper物件
  2. 遍歷LocalFileOffsetStore的offsetTable,將資料加入到OffsetSerializeWrapper的OffsetTable中
  3. OffsetSerializeWrapper轉為JSON
  4. 呼叫string2File方法將JSON資料保存到磁盤檔案
 public class LocalFileOffsetStore implements OffsetStore {
    @Override
    public void persistAll(Set<MessageQueue> mqs) {
        if (null == mqs || mqs.isEmpty())
            return;OffsetSerializeWrapper
        // 創建
        OffsetSerializeWrapper offsetSerializeWrapper = new OffsetSerializeWrapper();
        // 遍歷offsetTable
        for (Map.Entry<MessageQueue, AtomicLong> entry : this.offsetTable.entrySet()) {
            if (mqs.contains(entry.getKey())) {
                // 獲取拉取偏移量
                AtomicLong offset = entry.getValue();
                // 加入到OffsetSerializeWrapper的OffsetTable中
                offsetSerializeWrapper.getOffsetTable().put(entry.getKey(), offset);
            }
        }
        // 將物件轉為JSON
        String jsonString = offsetSerializeWrapper.toJson(true);
        if (jsonString != null) {
            try {
                // 將JSON資料保存到磁盤檔案
                MixAll.string2File(jsonString, this.storePath);
            } catch (IOException e) {
                log.error("persistAll consumer offset Exception, " + this.storePath, e);
            }
        }
    }
}

集群模式

集群模式下消費進度保存在Broker端,

更新進度

集群模式下的更新進度與廣播模式下的更新型別,都是只更新了offsetTable中的資料:

public class RemoteBrokerOffsetStore implements OffsetStore {
    
    private ConcurrentMap<MessageQueue, AtomicLong> offsetTable =
        new ConcurrentHashMap<MessageQueue, AtomicLong>();
    @Override
    public void updateOffset(MessageQueue mq, long offset, boolean increaseOnly) {
        if (mq != null) {
            // 獲取訊息佇列的進度
            AtomicLong offsetOld = this.offsetTable.get(mq);
            if (null == offsetOld) {
                // 將消費進度保存在offsetTable中
                offsetOld = this.offsetTable.putIfAbsent(mq, new AtomicLong(offset));
            }
            if (null != offsetOld) {
                if (increaseOnly) {
                    MixAll.compareAndIncreaseOnly(offsetOld, offset);
                } else {
                    // 更新拉取偏移量
                    offsetOld.set(offset);
                }
            }
        }
    }
}

加載

集群模式下加載消費進度需要從Broker獲取,在消費者發送訊息拉取請求的時候,Broker會計算消費偏移量,所以RemoteBrokerOffsetStore的load方法為空,什么也沒有干:

public class RemoteBrokerOffsetStore implements OffsetStore {
    @Override
    public void load() {
    }
}

持久化

由于集群模式下消費進度保存在Broker端,所以persistAll方法中呼叫了updateConsumeOffsetToBroker向Broker發送請求進行消費進度保存:

public class RemoteBrokerOffsetStore implements OffsetStore {
    @Override
    public void persistAll(Set<MessageQueue> mqs) {
        if (null == mqs || mqs.isEmpty())
            return;

        final HashSet<MessageQueue> unusedMQ = new HashSet<MessageQueue>();

        for (Map.Entry<MessageQueue, AtomicLong> entry : this.offsetTable.entrySet()) {
            MessageQueue mq = entry.getKey();
            AtomicLong offset = entry.getValue();
            if (offset != null) {
                if (mqs.contains(mq)) {
                    try {
                        // 向Broker發送請求更新拉取偏移量
                        this.updateConsumeOffsetToBroker(mq, offset.get());
                        log.info("[persistAll] Group: {} ClientId: {} updateConsumeOffsetToBroker {} {}",
                            this.groupName,
                            this.mQClientFactory.getClientId(),
                            mq,
                            offset.get());
                    } catch (Exception e) {
                        log.error("updateConsumeOffsetToBroker exception, " + mq.toString(), e);
                    }
                } else {
                    unusedMQ.add(mq);
                }
            }
        }
        // ...
    }
}

持久化的觸發

MQClientInstance在啟動定時任務的方法startScheduledTask中注冊了定時任務,定時呼叫persistAllConsumerOffset對拉取進度進行持久化,persistAllConsumerOffset中又呼叫了MQConsumerInnerpersistConsumerOffset方法:

public class MQClientInstance {
    private void startScheduledTask() {
        // ...
        // 注冊定時任務,定時持久化拉取進度
        this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    // 持久化
                    MQClientInstance.this.persistAllConsumerOffset();
                } catch (Exception e) {
                    log.error("ScheduledTask persistAllConsumerOffset exception", e);
                }
            }
        }, 1000 * 10, this.clientConfig.getPersistConsumerOffsetInterval(), TimeUnit.MILLISECONDS);
        // ...
    }
    
    private void persistAllConsumerOffset() {
        Iterator<Entry<String, MQConsumerInner>> it = this.consumerTable.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, MQConsumerInner> entry = it.next();
            MQConsumerInner impl = entry.getValue();
            // 呼叫persistConsumerOffset進行持久化
            impl.persistConsumerOffset();
        }
    }
}

DefaultMQPushConsumerImplMQConsumerInner的一個子類,以它為例可以看到在persistConsumerOffset方法中呼叫了offsetStore的persistAll方法進行持久化:

public class DefaultMQPushConsumerImpl implements MQConsumerInner {
    @Override
    public void persistConsumerOffset() {
        try {
            this.makeSureStateOK();
            Set<MessageQueue> mqs = new HashSet<MessageQueue>();
            Set<MessageQueue> allocateMq = this.rebalanceImpl.getProcessQueueTable().keySet();
            mqs.addAll(allocateMq);
            // 拉取進度持久化
            this.offsetStore.persistAll(mqs);
        } catch (Exception e) {
            log.error("group: " + this.defaultMQPushConsumer.getConsumerGroup() + " persistConsumerOffset exception", e);
        }
    }
}

總結

參考
丁威、周繼鋒《RocketMQ技術內幕》

RocketMQ版本:4.9.3

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/500290.html

標籤:Java

上一篇:day06-Java流程控制

下一篇:Java面向物件(八)

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more