千峰商城-springboot项目搭建-86-订单超时取消-定时任务查询超时未支付订单

订单超时取消:当用户成功提交订单之后在规定时间内如果没有完成支付,则将订单关闭,还原库存。
 
实现订单的超时取消通常有两种解决方案:
1.使用定时任务(循环扫描)(quartz)
2.延时队列(MQ)
 
一、流程分析

 

 


 

 二、实现

1.在service中的pom.xml中添加定时任务依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

 

 

2.在api子工程启动类中添加启动定时任务的注解@EnableScheduling

复制代码
@EnableScheduling
@SpringBootApplication
@MapperScan("com.qfedu.fmmall.dao")
public class ApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiApplication.class, args);
    }

}
复制代码

 

 

 3.在service包下新建job包

 

 job包下新建OrderTimeoutCheckJob类。

 

 

 OrderTimeoutCheckJob:
复制代码
@Component
public class OrderTimeoutCheckJob {
    
    @Autowired
    private OrdersMapper ordersMapper;
    
    @Scheduled(cron = "0/5 * * * * ?")
    public void checkAndCloseOrder(){
        //1.查询超过30分钟,订单状态依然为待支付状态的订单
        Example example = new Example(Orders.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status","1");

        Date time = new Date(System.currentTimeMillis() - 30*60*1000);
        criteria.andLessThan("createTime",time);

        List<Orders> orders = ordersMapper.selectByExample(example);

    }
}
复制代码

 

4.测试:

复制代码
    @Autowired
    private OrdersMapper ordersMapper;

   @Test
    public void test(){
        Example example = new Example(Orders.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status","1");

        Date time = new Date(System.currentTimeMillis() - 30*60*1000);
        criteria.andLessThan("createTime",time);

        List<Orders> orders = ordersMapper.selectByExample(example);
     for (int i = 0; i < orders.size(); i++) {
        System.out.println(orders.get(i).getOrderId()+"\t"
+orders.get(i).getCreateTime()+"\t"+orders.get(i).getStatus());
}

}
复制代码

 

 

 

 测试成功!

 

 

 
 
posted @   临易  阅读(381)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
点击右上角即可分享
微信分享提示