经典面试题:订单超时问题
问题引出
外卖、京东淘宝拼多多抖音商城下单、机票火车票门票、酒店饭店预定、上门服务、限时抽奖、限时优惠券……
候选解决方案
- 方案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