RocketMq详解:二、SpringBoot集成RocketMq

Springboot 整合RocketMQ 因为已经保存用户的基本信息,保存上状态标志位(0),消费者计算完后,根据id更新该数据标志位(1),计算异常问题更新标志位(2),每日定时任务对异常数据进行批量推送重新计算。根据用户提交的手机号计算用户数据,计算用户实时数据比较长数据量大的3-5分钟,数据小的1分钟上下,移动端不需要实时放回用户计算数据,所以接口保存完用户基本信息。此机制只能针对 消息队列宕机 网络异常或队列数据丢失问题。业务场景:该接口为H5、小程序提供,收集用户信息姓名、手机号、身份证号、地区等信息。4. 监听器事务配置。 阅读详情
AI摘要

本文介绍了如何使用RocketMQ实现消息的延迟发送,并提供了基于不同延迟等级的具体实现方案。

上一章:《RocketMq详解:一、RocketMQ 介绍及基本概念》



在上一章中我们对Rocket的基础知识、特性以及四大核心组件进行了详细的介绍,本章带着大家一起去在项目中具体的进行应用,并设计将其作为一个工具包只提供消息的分发服务和业务模块进行解耦

在进行本章的学习之前,需要确保你的可以正常启动和访问RocketMq服务,还未安装的可以移步至此:

1.添加maven依赖

		<dependency>
			<groupId>org.apache.rocketmq</groupId>
			<artifactId>rocketmq-spring-boot-starter</artifactId>
			<version>2.2.3</version>
		</dependency>

2.项目结构

在这里插入图片描述

3.配置管理

rocketmq:
  name-server: 127.0.0.1:9876
  # 生产者
  producer:
    group: boot_group_1
    # 消息发送超时时间
    send-message-timeout: 3000
    # 消息最大长度4M
    max-message-size: 4096
    # 消息发送失败重试次数
    retry-times-when-send-failed: 3
    # 异步消息发送失败重试次数
    retry-times-when-send-async-failed: 2
  # 消费者
  consumer:
    group: boot_group_1
    # 每次提取的最大消息数
    pull-batch-size: 5

上面的配置如果是在分布式环境下也可以配置在Apollo或nacos等配置中心里进行动态配置

4.配置类

在配置类中主要定义两个Bean的加载,即RocketMQTemplate和DefaultMQProducer,主要是提供消息发送的能力,即生产消息;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author ninesun
 * @ClassName RocketMqConfig
 * @description: 消息中间件配置类
 * @date 2024年05月19日
 * @version: 1.0
 */
@Configuration
public class RocketMqConfig {

    @Value("${rocketmq.name-server}")
    private String nameServer;

    @Value("${rocketmq.producer.group}")
    private String producerGroup;

    @Value("${rocketmq.producer.send-message-timeout}")
    private Integer sendMsgTimeout;

    @Value("${rocketmq.producer.max-message-size}")
    private Integer maxMessageSize;

    @Value("${rocketmq.producer.retry-times-when-send-failed}")
    private Integer retryTimesWhenSendFailed;

    @Value("${rocketmq.producer.retry-times-when-send-async-failed}")
    private Integer retryTimesWhenSendAsyncFailed;

    @Bean
    public RocketMQTemplate rocketMqTemplate() {
        RocketMQTemplate rocketMqTemplate = new RocketMQTemplate();
        rocketMqTemplate.setProducer(defaultMqProducer());
        return rocketMqTemplate;
    }

    @Bean
    public DefaultMQProducer defaultMqProducer() {
        DefaultMQProducer producer = new DefaultMQProducer();
        producer.setNamesrvAddr(this.nameServer);
        producer.setProducerGroup(this.producerGroup);
        producer.setSendMsgTimeout(this.sendMsgTimeout);
        producer.setMaxMessageSize(this.maxMessageSize);
        producer.setRetryTimesWhenSendFailed(this.retryTimesWhenSendFailed);
        producer.setRetryTimesWhenSendAsyncFailed(this.retryTimesWhenSendAsyncFailed);
        return producer;
    }
}

5.基础用法

5.1 消息生产

编写一个生产者接口类,分别使用RocketMQTemplate和DefaultMQProducer实现消息发送的功能,然后可以通过Dashboard控制面板查看消息详情

  • 编写Controller进行消息的发送
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class TestController01 {
    @Resource
    private RocketMQTemplate rocketMqTemplate;

    @Resource
    private DefaultMQProducer defaultMqProducer;

    /**
     * 利用rocketMqTemplate发送消息
     *
     * @return
     */
    @GetMapping("/send/msg1")
    public String sendMsg1() {
        try {
            // 构建消息主体
            Map<String, String> msgBody = new HashMap<>();
            msgBody.put("data", "利用rocketMqTemplate发送消息");
            // 发送消息
            rocketMqTemplate.convertAndSend("boot-mq-topic", JSON.toJSONString(msgBody));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "OK";
    }

    /**
     * 利用DefaultMQProducer发送消息
     * @return
     */

    @GetMapping("/send/msg2")
    public String sendMsg2() {
        try {
            // 构建消息主体,此处可以用对象代替,为了方便演示,使用map
            Map<String, String> msgBody = new HashMap<>();
            msgBody.put("data", "利用DefaultMQProducer发送消息");
            // 构建消息对象
            Message message = new Message();
            message.setTopic("boot-mq-topic");
            message.setTags("boot-mq-tag");
            message.setKeys("boot-mq-key");
            message.setBody(JSON.toJSONString(msgBody).getBytes());
            // 发送消息,打印日志
            SendResult sendResult = defaultMqProducer.send(message);
            log.info("msgId:{},sendStatus:{}", sendResult.getMsgId(), sendResult.getSendStatus());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "OK";
    }
}

自己自行测试,访问这两个接口后,我们可以在Dashboard控制面板查看到:
在这里插入图片描述

5.2 消息消费者

接下来,我们创建一个消息消费者。在Spring Boot项目中,我们可以使用@RocketMQMessageListener注解来定义一个消息消费者。

import com.alibaba.fastjson.JSON;
import com.example.demo.po.MessageData;
import com.example.demo.po.User;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

/**
 * @author hb24795
 * @ClassName BootMqConsumer
 * @description: 消费者
 * @date 2024年05月26日
 * @version: 1.0
 */
@Service
@RocketMQMessageListener(topic = "boot-mq-topic", consumerGroup = "boot_group_1")
public class BootMqConsumer implements RocketMQListener<String> {
    @Override
    public void onMessage(String message) {
        System.out.printf("------- StringConsumer received:");
        System.out.println(message);
    }
}

当然你可以设置更多的消费前置条件:

@Component
@RocketMQMessageListener(topic = "your_topic_name", consumerGroup = "your_consumer_group_name",selectorExpression = "your_tag", selectorType = ExpressionType.TAG)
public class MyConsumer implements RocketMQListener<String> {

    @Override
    public void onMessage(String message) {
        // 处理消息的逻辑
        System.out.println("Received message: " + message);
    }
}

注意:此处的consumerGroup要和我们配置的group对应
在这里插入图片描述

在这里插入图片描述

上面我们已经完成了一个基本的从消息发送到消息消费的逻辑,大家可以在自己的项目中结合设计模式,aop等来定制化自己的消息中间件,但是消息的类型远不止这几个,在实现之前我们先把消息的发送代码和我们的业务代码进行解耦

@Component
public class MessageProduct {
    @Resource
    private RocketMQTemplate rocketMqTemplate;
    @Resource
    private DefaultMQProducer defaultMqProducer;

    public SendResult SendMessage(String topic, Object data, List<String> keys, String tags) throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
        Message message = new Message();
        if (StringUtils.isBlank(topic)) {
            return null;
        } else {
            message.setTopic(topic);
        }
        if (data != null) {
            message.setBody(JSON.toJSONString(data).getBytes());
        }
        if (!CollectionUtils.isEmpty(keys)) {
            message.setKeys(keys);
        }
        if (StringUtils.isBlank(tags)) {
            message.setTags(tags);
        }
        message.setBody(JSON.toJSONString(data).getBytes());
        // 发送消息,打印日志
        return defaultMqProducer.send(message);
    }
}

5.3 延迟消息

RocketMQ 支持延迟消息发送,但并非任意时间,而是有特定的延迟等级。在较旧的版本中,延迟等级从1到18,每个等级对应一个固定的延迟时间范围。然而,随着RocketMQ的更新发展,其对于延迟消息的支持变得更加灵活。

根据最新的资料,RocketMQ 5.x版本支持的最大延迟时间可以非常长,可达一年之久,这意味着在一定意义上,它能够满足大部分应用场景对于延迟消息的需要,尽管这并不等同于可以任意指定任意时间精度的延迟。

我们先看看必须通过指定的等级进行延迟的实现:

RocketMQ不支持任意时间的延迟,只有18个等级的延迟时间,默认是:1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h。从头到尾共18个等级时间,s、m、h、d,分别表示秒、分、时、天。

默认的18个等级对应的时间可以修改,在broker.conf中增加如下配置,根据自身需求修改时间,然后重启broker。

1、延迟消息的原理

如果让你来设计RocketMQ的延迟消息,你会怎么设计?
1.延迟消息也是个消息,只是多了延迟时间,既然是消息,不管是不是要立刻处理,先找个临时Topic存储起来。

2.Topic里面实际上是一个个队列,那所有的延迟消息要存在一个队列里吗?不要放在同一个队列里,因为消息各自都有不同的延迟时间,如果放在一个队列里,会牵扯到其余问题:比如排序、比如记录消费位置等。所以是按延迟时间分开存。

3.消息已经存起来了,那怎么处理呢?既然涉及到了延迟时间,那自然启动线程去定时获取消息,判断消息的延迟时间是否已经到达,到达之后则取出来投放到目的Topic。

讲到这里,延迟消息的架构图基本浮现出来了:
在这里插入图片描述

实际上RocketMQ在设计延迟消息时,跟上面的思路基本类似,不在赘述,额外补充几点:

1.消息进入Broker后,会被存储在TopicSCHEDULE_TOPIC_XXXX中,只是在Dashboard中看不到。
TopicSCHEDULE_TOPIC_XXXX中有18个消息队列,分别存储18个延迟等级对应的消息。

2.RocketMQ 在启动时,会从broker.conf中获取18个等级对应的时间,延迟等级和时间的关系会存在放到DelayLevelTable中。

3.RocketMQ会开启18个定时任务每隔100ms,从TopicSCHEDULE_TOPIC_XXXX判断18个队列里的第一个消息是否可以被投放,如果可以投放,则在投放到原本的目的Topic。
判断逻辑:存入时间+延迟时间 > 当前时间。
在这里插入图片描述

说到这里,估计你也能猜到,为什么不支持自定义延迟时间了,核心原因还是性能问题。

试想一下,如果设计成任意时间,那么就不可能使用18个队列了,更不可能使用无限个队列了,只可能使用单个队列。

但是如果使用单个队列,按照先进先出的存放的话,那出现需要后进先出的消息怎么办?那只能对整个队列进行排序,如果消息量很大,每次有消息进来都需要排序,那CPU肯定会被玩爆。

而且队列里的消息被消费后,都会记录偏移量,如果每次有消息进来都要排序,那偏移量则失去意义,增加了消息丢失的风险。

所以,RocketMQ的这种18个延迟时间等级的设计,虽然在延迟时间的自由度上作出了妥协,但是基本满足业务,性能也很优秀。

2.具体实现

我们对上面的通用发送进行修改:

    public SendResult SendMessage(String topic, Object data, List<String> keys, String tags, Integer delayLevel) throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
        Message message = new Message();
        if (StringUtils.isBlank(topic)) {
            return null;
        } else {
            message.setTopic(topic);
        }
        if (data != null) {
            message.setBody(JSON.toJSONString(data).getBytes());
        }
        if (!CollectionUtils.isEmpty(keys)) {
            message.setKeys(keys);
        }
        if (StringUtils.isBlank(tags)) {
            message.setTags(tags);
        }
        if (delayLevel != null) {
            message.setDelayTimeLevel(delayLevel);
        }
        message.setBody(JSON.toJSONString(data).getBytes());
        // 发送消息,打印日志
        return defaultMqProducer.send(message);
    }

此处设置的等级5,可能对应1分钟的延迟,但具体等级和时间的映射关系可以根据RocketMQ服务器的配置有所不同
我们测试一下:

    @GetMapping("/send/msg2")
    public String sendMsg2() {
        try {
            // 构建消息主体,此处可以用对象代替,为了方便演示,使用map![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/3799dce071c44aec923eb35d5a418f2e.png#pic_center)

            User user = User.builder()
                    .id(1)
                    .name("ninesun")
                    .build();
            SendResult sendResult = messageProduct.SendMessage("boot-mq-topic", user, Collections.singletonList(user.getId().toString()), null, null);
            log.info("msgId:{},sendStatus:{}", sendResult.getMsgId(), sendResult.getSendStatus());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "OK";
    }

如果我们想实现任意时间的延迟,可以利用上面的延迟等级进行实现

我只需要根据自定义的延迟时间获取延迟等级
首先自定义一个消息体,用于存储必要的信息

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class DelayMessageDTO<T> {
    private T data;
    private Integer delayTime;
    private String topic;

    private List<String> keys;
    private String tags;
}

设计一个简单的算法用于获取延迟等级

private static final Integer[] delayTimes = {1, 5, 10, 30, 60, 120, 180, 240, 300, 360, 420, 480, 540, 600, 1200, 1800, 3600, 7200};
  private Integer getDelayLevel(Integer delayTime) {
        if (delayTime == null || delayTime == 0) {
            return null;
        }
        for (int i = 0; i < delayTimes.length; i++) {
            int level = i + 1;
            if (delayTime.equals(delayTimes[i])) {
                return level;
            }
            if (delayTime > delayTimes[i] && delayTime < delayTimes[i + 1]) {
                return level;
            }

        }
        return null;

    }

新增一个消费者专门用于处理该消息的延迟

@Service
@RocketMQMessageListener(topic = "delay-consumer-topic", consumerGroup = "boot_group_1")
@Slf4j
public class DelayMqConsumer implements RocketMQListener<String> {
    @Resource
    MessageProduct messageProduct;

    @Override
    public void onMessage(String message) {
        log.info("收到延迟消费消息,消息:{}", message);
        System.out.println(message);
        DelayMessageDTO delayMessageDTO = JSON.parseObject(message, DelayMessageDTO.class);
        log.info("剩余:{}s", delayMessageDTO.getDelayTime());
        try {
            messageProduct.SendDelayMessage(delayMessageDTO);
        } catch (MQBrokerException e) {
            throw new RuntimeException(e);
        } catch (RemotingException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (MQClientException e) {
            throw new RuntimeException(e);
        }
    }
}

消息的发送

    public SendResult SendDelayMessage(DelayMessageDTO data) throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
        // 发送消息,打印日志
        if (data == null) {
            return null;
        }
        Integer delayLevel = this.getDelayLevel(data.getDelayTime());
        if (delayLevel == null) {
            return this.SendMessage(data.getTopic(), data, data.getKeys(), data.getTags(), delayLevel);
        }
        Integer delayTime = data.getDelayTime() - delayTimes[delayLevel - 1];
        data.setDelayTime(delayTime);
        return this.SendMessage("delay-consumer-topic", data, data.getKeys(), data.getTags(), delayLevel);
    }

在这里插入图片描述

在这里插入图片描述

至此我们就可以简单的实现一个消息的任意时间延迟,但是实际的延迟实现中,我们并不推荐该延迟方式,因为这种延迟完全依赖于mq的性能,如果遇到消息的积压等,我们的延迟将变得十分不可靠,很多开源社区中推荐:

  • 外部存储与调度:将消息和期望的发送时间存储到数据库或缓存中(如Redis),然后使用一个定时任务(如Quartz、Spring Scheduler)定期检查这些存储的消息,当达到预定时间时,再通过DefaultMQProducer发送出去。
  • 利用死信队列与TTL:虽然这不是直接实现任意时间延迟的方式,但可以通过设置消息的TTL(生存时间)和死信队列机制间接实现。消息到期后成为死信,触发特定逻辑进行处理或重定向到另一个队列进行实际发送。

在RocketMQ5.0版本,支持任意时段的延迟消息。在Github中最新的版本中已经解决了这个问题,[ISSUE #6203] Allow to publish delay message with arbitrary timestamp #6204

如果还未安装,可以参考:《MacOS环境下RocketMQ5.0+安装及部署 RocketMQ Dashboard 可视化》

6.基于RocketMQ5.0+实现任意时间的消息延迟

RocketMQ 5.0+ 通过引入 ​​时间轮算法(Timing Wheel)​​ 实现任意时间精度的延迟消息调度,其底层原理结合了多级时间轮结构、异步任务调度和持久化存储机制。

1.时间轮算法的核心设计

RocketMQ 5.0+ 通过引入 ​​时间轮算法(Timing Wheel)​​ 实现任意时间精度的延迟消息调度,其底层原理结合了多级时间轮结构、异步任务调度和持久化存储机制。以下是核心实现原理的详细分析:

一、时间轮算法的核心设计
RocketMQ 5.0 的时间轮采用 ​​多层分片结构​​(Hierarchical Timing Wheel),类似时钟的时针、分针、秒针,每层时间轮负责不同时间粒度的任务调度:

​​层级划分​​:

  • ​​底层时间轮​​:以 ​​秒级​​ 为刻度(如 1ms/tick),处理短期延迟任务(例如 1 秒到 1 小时)。
  • ​​高层时间轮​​:以 ​​分钟级​​ 或 ​​小时级​​ 为刻度,处理长期延迟任务(例如 2 小时到 3 天)。
  • ​​任务降级​​:当高层时间轮的任务到期后,自动降级到下层时间轮继续调度,确保时间精度和吞吐量的平衡。
    ​​

时间轮参数​​:

  • ​​刻度数量​​:默认支持 ​​2 天​​ 的延迟范围(通过多层时间轮组合实现)。
  • ​​刻度精度​​:默认 1 秒,可通过配置调整(例如拆分为毫秒级刻度)

2.延迟消息的存储与调度流程

消息转换与存储​​

​​消息转换​​:生产者发送延迟消息时,Broker 将其转换为 TimerRequest 对象,并设置目标投递时间戳(deliverTimeMs)。

​​持久化存储​​:

  • 消息写入 ​​CommitLog​​(与普通消息类似),但 Topic 被替换为系统 Topic rmq_sys_wheel_timer。
  • 时间轮的槽位信息记录在 ​​TimerLog​​ 文件中(定长 100MB),确保消息持久化。

时间轮调度​

入队逻辑​​:

  • 根据延迟时间计算目标槽位,若延迟超过当前时间轮范围,则滚动到高层时间轮。
  • 例如,延迟 3 天的消息会存储在高层时间轮的对应槽位。

​​出队逻辑​​:

  • 时间轮指针每秒推进一次,触发当前槽位的所有到期消息。
  • 到期消息通过 ​​TimerDequeuePutService​​ 线程投递到原始 Topic 的消费队列。

关键优化

异步调度与流控​:

  • 异步处理​​:时间轮的推进和消息投递通过独立线程池(如 TimerEnqueuePutService)完成,避免阻塞主线程。
  • ​​流控机制​​:每个时间轮槽位设置阈值,防止消息堆积导致内存溢出。

消息恢复与容灾​​:

  • ​​故障恢复​​:Broker 重启后,通过加载 TimerLog 文件重建时间轮状态,确保未投递消息不丢失。
  • ​​数据一致性​​:消息投递前会校验 CommitLog 中的原始内容,避免数据损坏。

高并发优化​​

  • ​​批量投递​​:同一槽位的到期消息批量触发投递,减少线程上下文切换。
  • ​​随机延迟​​:对同时到期的消息添加随机抖动,避免单时间点投递压力过大

3.核心存储组件

RocketMQ 5.0 的延迟消息存储数据结构设计围绕 ​​时间轮算法​​ 展开,核心是通过 ​​TimerLog​​ 和 ​​TimerWheel​​ 两个关键文件实现高效存储与调度。以下是其存储结构的详细解析:

3.1 TimerLog(定时消息日志文件)​

功能​​:记录所有延迟消息的元数据,按时间顺序追加写入,支持快速定位到期的消息。

文件结构​​:

  • ​​固定大小​​:默认 37MB(可配置),采用定长格式存储。
  • ​​记录格式​​:
public class TimerLogRecord {
    long prevPos;       // 前一条记录在 TimerLog 中的位置(链式结构)
    long deliverTimeMs; // 消息到期时间戳(毫秒级)
    long commitLogPos;  // 消息在 CommitLog 中的物理位置
    int msgSize;        // 消息体长度
    byte[] msgBody;     // 消息体(可选,根据配置决定是否存储)
}
  • ​​链式索引​​:通过 prevPos 实现消息的链式关联,避免全量扫描,提升读取效率

​​3.2 TimerWheel(时间轮槽位文件)​

功能​​:管理时间轮的刻度槽位,每个槽位指向 TimerLog 中对应时间段的消息起始位置。

​​数据结构​​:

  • ​​数组形式​​:默认包含 ​​2 天​​ 的时间刻度(每个刻度代表 1 秒),总槽数为 2 * 24 * 60 * 60 = 172800。
  • ​​槽位对象(Slot)​​:
public class Slot {
    long firstPos;      // 槽位第一条消息在 TimerLog 中的位置
    long lastPos;       // 槽位最后一条消息在 TimerLog 中的位置
    int num;            // 槽位当前消息数量
    long timeMs;        // 槽位对应的时间戳(毫秒级)
}

​​时间轮指针​​:通过 currentTimeMs 指针标识当前时间位置,每秒推进一次,触发槽位消息处理。

3.3 消息存储流程

1.消息写入阶段​​

​​1.替换 Topic​​:延迟消息写入时,Broker 将其原始 Topic 和 Queue ID 替换为系统 Topic rmq_sys_wheel_timer,并记录到消息的扩展属性中。
​​
2.持久化路径​​:

  • ​​TimerLog​​:消息元数据(到期时间、CommitLog 位置等)追加写入 TimerLog 文件。
  • ​​TimerWheel​​:根据消息的 deliverTimeMs 计算时间偏移量,定位到对应的 Slot,并更新 Slot 的 firstPos 和 lastPos。
2.消息调度阶段​​

​​时间轮推进​​:定时任务(如 TimerDequeuePutService)每秒将时间轮指针前移一格,检查当前 Slot 的消息。

​​消息拉取​​:从当前 Slot 的 firstPos 开始,通过链式索引(prevPos)遍历 TimerLog,批量拉取到期消息。

​​消息投递​​:将到期消息恢复原始 Topic 和 Queue ID,重新写入 CommitLog,并通知消费者消费

针对上面这个流程其底层同样做了很多的优化和设计:

3.4 关键优化设计

1.​分层存储与流控​​

  • ​​冷热分离​​:TimerLog 仅存储消息索引,原始数据仍存于 CommitLog,减少重复存储。
  • ​​批量处理​​:同一 Slot 的消息批量拉取和投递,降低 I/O 和网络开销。

2.​​容灾与恢复

  • 文件持久化​​:TimerLog 和 TimerWheel 均采用文件存储,Broker 重启后可通过文件重建时间轮状态。
  • ​​一致性校验​​:投递前校验 CommitLog 中的消息完整性,避免数据丢失。

3.高并发支持​​

  • ​​多线程处理​​:通过线程池(如 TimerDequeueGetMessageService)并行处理不同 Slot 的消息。
  • ​​随机抖动​​:对同时到期的消息添加随机延迟,分散投递峰值压力

4.适用场景与注意事项

适用场景​​:订单超时、定时任务、缓存失效等需精确控制时间的场景。

​​注意事项​​:

  • ​​最大延迟限制​​:默认支持 2 天,需通过配置调整 TimerWheel 的时间范围。
  • ​​资源监控​​:需监控 TimerLog 和 TimerWheel 的文件大小及内存占用。
  • 业务层优化​​:避免大量消息集中在同一时刻到期,建议添加随机延迟。

通过 ​​TimerLog​​ 和 ​​TimerWheel​​ 的协同设计,RocketMQ 5.0 实现了高吞吐、低延迟的延迟消息调度,解决了传统延迟队列的固定时间粒度限制问题。

5.与传统延迟队列的对比

在这里插入图片描述

6.实战

为了使我们的消息发送方法更加通用,在后续的章节中我们的消息内容均使用下面这个对象:

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class MessageDTO<T> {
    private T data;
    private Integer delayTime;
    private String topic;
    private String key;
    private List<String> keys;
    private String tags;
}
  • 消息生产者
@Component
public class MessageProduct {
    @Resource
    private RocketMQTemplate rocketMqTemplate;

  
    public SendResult SendMessage(MessageDTO data) {
          // 创建一个Message对象
        org.springframework.messaging.Message<?> message = MessageBuilder.withPayload(JSON.toJSONString(data))
                .setHeader(RocketMQHeaders.KEYS,data.getKey())
                .setHeader(RocketMQHeaders.TAGS,data.getTags())
                .build();
        return rocketMqTemplate.syncSendDelayTimeSeconds(data.getTopic(), message, data.getDelayTime());
    }

}
  • 消费者
@Service
@RocketMQMessageListener(topic = "boot-mq-topic", consumerGroup = "boot_group_1")
@Slf4j
public class BootMqConsumer implements RocketMQListener<MessageDTO> {
    @Override
    public void onMessage(MessageDTO message) {
        log.info("收到延迟消息成功,消息体:{}", message);
    }

}
  • 测试
  @GetMapping("/send/msg4")
    public String sendMsg4() {
        try {
            // 构建消息主体,此处可以用对象代替,为了方便演示,使用map
            User user = User.builder()
                    .id(1)
                    .name("ninesun")
                    .build();
            MessageDTO<User> messageDTO = new MessageDTO<>();
            messageDTO.setData(user);
            messageDTO.setDelayTime(10);
            messageDTO.setTopic("boot-mq-topic");
            messageDTO.setKeys(Collections.singletonList(user.getId().toString()));
            SendResult sendResult = messageProduct.SendMessage(messageDTO);
            log.info("msgId:{},sendStatus:{},data:{}", sendResult.getMsgId(), sendResult.getSendStatus(), JSON.toJSONString(messageDTO));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "OK";
    }

可以看到:
在这里插入图片描述
至此我们已经掌握了最基本的消息队列的使用


下一章:《RocketMq详解:三、RocketMq通用生产和消费方法改造》

2024/11/30 RocketMQ本机安装与SpringBoot整合 RocketMQ是由阿里捐赠给Apache的一款低延迟、高并发、高可用、高可靠的分布式消息中间件。经历 了淘宝双十一的洗礼。RocketMQ既可为分布式应用系统提供异步解耦和削峰填谷的能力,同时也具备互联网应用所需的海量消息堆积、高吞吐、可靠重试等特性。官方文档:github中文主页: 阅读详情

相关推荐

SpringBoot与RocketMQ安全通信实践:基于ACL的access-key/secret-key动态鉴权

本文详细介绍了在SpringBoot项目中为RocketMQ配置ACL安全通信的实践方案。针对静态配置密钥的痛点,重点阐述了如何实现基于access-key和secret-key的动态鉴权机制,通过自定义工厂或环境后处理器,从安全源动态获取密钥,从而提升微服务架构下的消息队列安全性,并遵循最小权限原则进行密钥管理。

plant的博客 681

【SpringBoot高级篇】SpringBoot集成RocketMQ消息队列

RocketMQ是阿里巴巴2016年MQ中间件,使用Java语言开发,在阿里内部,RocketMQ承接了例如“双11”等高并发场景的消息流转,能够处理万亿级别的消息。

输入技术、输出想法 2万+

RocketMQ入坑指南(五):SpringBoot集成RocketMQ和具体使用方式

经过前面几章的学习,本章内容着重介绍了Springboot如何集成RocketMQ,如何发送普通消息、顺序消息、延时消息和事务消息,示例代码已上传CSDN

u014374743的博客 3888

Springboot快速集成RocketMQ

零基础,Springboot快速集成RocketMQ

huangtenglong的博客 6714

SpringBoot集成RocketMQ(附带集成工具类)

1. pom文件引入rocketmq的client端依赖 <!--rocketmq--> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-client</artifactId> <version>4.3.0</ver

weixin_38399962的博客 4102

RocketMQ(一):Linux安装RocketMQ和常用命令

下载安装 版本:4.8.0 下载地址:https://www.apache.org/dyn/closer.cgi?path=rocketmq/4.8.0/rocketmq-all-4.8.0-source-release.zip 下载成功后,上传到 /opt 目录,并解压

qq_28834355的博客 1603

Springboot集成RocketMQ

什么是RocketMQ? 官方说明: 随着使用越来越多的队列和虚拟主题,ActiveMQ IO模块遇到了瓶颈。我们尽力通过节流,断路器或降级来解决此问题,但效果不佳。因此,我们那时开始关注流行的消息传递解决方案Kafka。不幸的是,Kafka不能满足我们的要求,特别是在低延迟和高可靠性方面。 看到这里可以很清楚的知道RcoketMQ 是一款低延迟、高可靠、可伸缩、易于使用的消息中间件。 具...

lockie的博客 20万+

【SpringBoot深入浅出系列】SpringBoot之集成RocketMQ

1、新建springboot项目,pom中添加以下依赖

邓邓子的博客 5112

SpringBoot集成RocketMQ

MQ(Message Queue)是一种跨进程的通信机制,用于传递消息。使用MQ之后可以实现异步解耦和流量消峰的功能。在微服务项目中是一个常用的组件。RocketMQ的使用需要先启动RocketMQ的服务,这样才可以在后端连接RocketMQ并使用RocketMQ传递消息。

Ahjbvj的博客 7272

实战指南:如何用DCCRN模型提升语音增强效果(附代码示例)

本文提供了基于DCCRN模型进行语音增强的实战指南。通过深入解析复数网络如何协同处理语音的幅度与相位信息,并附有完整的PyTorch代码实现,帮助开发者从数据准备、模型搭建到训练调优,构建高效的实时语音增强系统,有效提升嘈杂环境下的语音清晰度。

weixin_29054245的博客 489

Chapter 7 Linear Voltage Regulators

这一章我们介绍LDO.

2304_76736886的博客 2784

springboot集成rocketmq

  本文是springboot集成rocketmq的入门篇,主要介绍单机环境下安装rocketmq,并集成到springboot框架中,实现字符串类型消息的生产和消费。   1)高可用集群部署方案请参考 待更新。。。   2)更多使用方式请参考 待更新。。。 一、下载、安装、启动 1、下载 http://rocketmq.apache.org/dowloading/releases/ 2、安装 ...

猴子哥哥的博客 1441

深入掌握英飞凌TriCore中断向量表

摘要:本文探讨了英飞凌Tc277芯片中断机制的原理与实现,重点解析了中断向量表基地址的链接文件定义方式、BIV寄存器的初始化过程以及每个中断条目的32字节空间分配规则。通过分析中断向量号(1-255)的计算方法,阐明了中断条目跳转地址(如STM0中断向量号37对应0x800F04A0)的生成逻辑。文章还揭示了.map文件中14字节跳转指令的组成原理,以及最终通过a14寄存器跳转到实际中断函数(如stm0Sr0ISR)的执行流程,为嵌入式开发人员理解中断处理机制提供了清晰的技术路径。

IT技术猿猴的博客 1721

RocketMQ(三):集成SpringBoot

需要创建两个服务,消息生产服务和消息消费者服务。生产消息存在多个服务,消费则统一由一个服务处理。过滤模式有两种:正则表达式和sql92方式。keys从MessageExt对象中获取。获取带key和tag的消费者。

从基础到源码解析的学习记录 1594

【BigWorld 游戏服务器引擎】Cell 架构设计介绍,及Java实现方案的探索

横向扩展(Scalability):通过动态增减CellApp和BaseApp的数量,可以轻松应对玩家人数的变化。世界可以做得非常大,只需增加更多的 Cell。负载分离(Load Separation):将不同性质的负载分离,避免了单一进程瓶颈。CPU 密集型的实时计算(CellApp)和 I/O 密集型的数据操作(BaseApp)互不影响。高效的视野管理(AOI):每个 Cell 只关心自己区域内和边界上的实体,大大降低了计算复杂度。容错性:某个CellApp。

代码时光 1234

ArcGIS新手必看:5分钟搞定等高线转DEM栅格(附完整操作截图)

本文详细介绍了在ArcGIS中将等高线转换为DEM栅格的完整流程,包括CAD数据预处理、TIN转栅格和直接插值法两种核心方法,以及常见问题排查与优化技巧。通过实战案例和操作截图,帮助GIS新手快速掌握这一测绘数据处理的核心技能,提升地形分析和三维可视化效率。

dapp9builder的博客 290

SpringBoot 集成 RocketMQ

RocketMQ 主要由 Producer、Broker、Consumer 三部分组成,其中 Producer 负责生产消息,Consumer 负责消费消息,Broker 负责存储消息。Broker 在实际部署过程中对应一台服务器,每个 Broker 可以存储多个 Topic 的消息,每个Topic 的消息也可以分片存储于不同的 Broker。消息中转角色,负责存储消息、转发消息。表示一类消息的集合,每个主题包含若干条消息,每条消息只能属于一个主题,是RocketMQ 进行消息订阅的基本单位。

魂-淡 8277

海波龙(Hyperion,现属 Oracle)合并报表以 HFM(Hyperion Financial Management)为核心系统,方法论核心是以控制为基础确定合并范围,通过维度建模统一数据口径

摘要:海波龙合并报表系统(HFM)采用"规则驱动、维度建模"的方法论,通过四个核心环节实现自动化合并:确定合并范围、数据标准化、自动抵销调整及报表生成。系统支持多会计准则,以控制为基础划分合并方法(完全合并/权益法/成本法),通过维度建模统一数据口径,自动处理内部交易抵销、外币折算等复杂操作。业务操作流程涵盖数据采集、转换、抵销调整到报表生成全过程,关键控制点包括内部交易匹配、股权变动处理等。最终输出合规合并报表及完整审计线索,满足监管与管理需求。(150字)

金牌架构师 1312

springboot中rocketmq的集成与使用

消息队列rocketmq是Apache旗下的开源项目(原是Alibaba开源的项目),当springboot盛行后,Apache团队开源了rocketmq-spring来帮助我们在springboot中快速集成rocketmq,只需引入rocketmq-spring-boot-starter即可。 rocketmq-spring不仅实现了自动配置功能,个人认为最主要还是封装了spring-mes...

相逢一笑 7089

【RT-DETR涨点改进】全网独家创新、细节涨点改进篇 | AAAI 2025 | 将 CEM 颜色增强模块引入RT-DETR ,目标检测不再惧怕雾天和低光检测、小目标检测、遥感目标检测高效涨点

本文提出了一种新型结构引导去雾网络(SGDN),通过双色引导桥(BGB)和色彩增强模块(CEM)有效解决雾霾图像去雾问题。BGB利用YCbCr空间的纹理特征引导RGB特征恢复,CEM通过聚合YCbCr通道信息增强RGB色彩感知。实验证明该方法在真实雾霾数据集上优于现有技术,能同时保持色彩准确性和纹理清晰度。文章还提供了完整的代码实现和模型配置指南,包括三种改进版RT-DETR网络结构(rtdetr-l/r18/r50-CEM.yaml),为图像去雾和目标检测任务提供了实用解决方案。

Ai缝合怪、助力小伙伴高效发论文 357

ROS机器人未知环境自主探索功能包explore_lite最全源码详细解析(五)

本系列文章主要针对ROS机器人常使用的未知环境自主探索功能包explore_lite展开全源码的详细解析,并进行概括总结。 本系列文章共包含六篇文章,前五篇文章主要介绍explore_lite功能包中 explore.cpp、costmap_tools.h、frontier_search.cpp、costmap_client.cpp等源码实现文件中全部函数的详细介绍,第六篇文章进行概括总结,包含自主探索功能包explore_lite的简介,实现未知环境自主探索功能的原理及流程总结,效果演示,使用功能包exp

慕羽★的博客 1516

RocketMQ 学习教程——(二)SpringBoot 集成 RocketMQ

RocketMQ 学习教程——(二)SpringBoot 集成 RocketMQ

赵士杰——成功并非一蹴而就,而是在持之以恒的努力中逐渐实现。 5892

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

RocketMQ入门教程(二):SpringBoot集成RocketMQ

1. pom.xml <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-client</artifactId> <version>4.8.0</version> </dependency> 2. applicaton.yml server: port: 8888 rocketmq:

人不风流枉少年 2040

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

从 0 到 1 精通 SpringBoot 集成 RocketMQ

本文全面介绍SpringBoot集成RocketMQ的实践方案。RocketMQ作为阿里开源的高性能消息中间件,具备高吞吐量、低延迟和高可靠性特点,支撑了双11等大促场景。文章从核心概念、环境搭建入手,详细讲解基础集成步骤,包括消息生产者/消费者实现、控制器测试等。重点剖析高级特性:支持Tag/SQL92过滤的消息过滤机制、解决分布式事务的事务消息实现、延时消息功能以及消息重试机制。通过订单创建等实际案例,展示事务消息与数据库交互的完整流程,并给出消息轨迹跟踪方案。

果酱 の 博客 1507
上一篇: RocketMq详解:一、RocketMQ 介绍及基本概念
下一篇: docker安装rocketMq5x以上的版本
ZNineSun
ZNineSun 领域专家: 后端开发技术领域 领域专家: 后端开发技术领域
博客等级 码龄8年 3万+粉丝 506原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZNineSun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值