经典面试题:订单超时问题(1)

经典面试题:订单超时问题

问题引出

外卖、京东淘宝拼多多抖音商城下单、机票火车票门票、酒店饭店预定、上门服务、限时抽奖、限时优惠券……
支付剩余时间

候选解决方案

  • 方案1:定时任务Scheduled
  • 方案2:延时队列DelayQueue
  • 方案3:时间轮算法HashedWheelTimer
  • 方案4:Redis事件通知机制
  • 方案5:MQ消息队列

方案1:定时任务Scheduled

(好用又方便,首选SpringBoot)

方案思路

1. 使用数据库或缓存来保存订单数据;
2. Spring框架内置的Scheduled组件来做定时器;
3. 指定间隔时间获取未付款订单,逐条检查是否过期。

(示例代码仅展示核心的“超时”逻辑)

依赖、配置和核心代码

pom.xml

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
    </parent>
    
    <dependencies>
    	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <!-- hutool工具包,非必要 -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.3</version>
        </dependency>
        
        <!-- lombok,非必要 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

没有任何特殊依赖,就是一个普通SpringBoot项目


application.yml

server:
  port: 18080

spring:
  application:
    name: springboot-commontest

也没有任何特殊配置


import cn.hutool.core.thread.ThreadUtil;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

@EnableScheduling   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值