关于后端:订单30分钟未支付自动取消怎么实现

9次阅读

共计 10424 个字符,预计需要花费 27 分钟才能阅读完成。

目录

  • 理解需要
  • 计划 1:数据库轮询
  • 计划 2:JDK 的提早队列
  • 计划 3:工夫轮算法
  • 计划 4:redis 缓存
  • 计划 5:应用音讯队列

理解需要

在开发中,往往会遇到一些对于延时工作的需要。最全面的 Java 面试网站

例如

  • 生成订单 30 分钟未领取,则主动勾销
  • 生成订单 60 秒后, 给用户发短信

对上述的工作,咱们给一个业余的名字来形容,那就是延时工作。那么这里就会产生一个问题,这个延时工作和定时工作的区别到底在哪里呢?一共有如下几点区别

定时工作有明确的触发工夫,延时工作没有

定时工作有执行周期,而延时工作在某事件触发后一段时间内执行,没有执行周期

定时工作个别执行的是批处理操作是多个工作,而延时工作个别是单个工作

上面,咱们以判断订单是否超时为例,进行计划剖析

本文曾经收录到 Github 仓库,该仓库蕴含 计算机根底、Java 根底、多线程、JVM、数据库、Redis、Spring、Mybatis、SpringMVC、SpringBoot、分布式、微服务、设计模式、架构、校招社招分享 等外围知识点,欢送 star~

Github 地址

如果拜访不了 Github,能够拜访 gitee 地址。

gitee 地址

计划 1:数据库轮询

思路

该计划通常是在小型我的项目中应用,即通过一个线程定时的去扫描数据库,通过订单工夫来判断是否有超时的订单,而后进行 update 或 delete 等操作

实现

能够用 quartz 来实现的,简略介绍一下

maven 我的项目引入一个依赖如下所示

<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.2</version>
</dependency>

调用 Demo 类 MyJob 如下所示

package com.rjzheng.delay1;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class MyJob implements Job {public void execute(JobExecutionContext context) throws JobExecutionException {System.out.println("要去数据库扫描啦。。。");
    }

    public static void main(String[] args) throws Exception {
        // 创立工作
        JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                .withIdentity("job1", "group1").build();
        // 创立触发器 每 3 秒钟执行一次
        Trigger trigger = TriggerBuilder
                .newTrigger()
                .withIdentity("trigger1", "group3")
                .withSchedule(
                        SimpleScheduleBuilder
                                .simpleSchedule()
                                .withIntervalInSeconds(3).
                                repeatForever())
                .build();
        Scheduler scheduler = new StdSchedulerFactory().getScheduler();
        // 将工作及其触发器放入调度器
        scheduler.scheduleJob(jobDetail, trigger);
        // 调度器开始调度工作
        scheduler.start();}

}

运行代码,可发现每隔 3 秒,输入如下

要去数据库扫描啦。。。

长处

简单易行,反对集群操作

给大家分享一个 Github 仓库,下面有大彬整顿的 300 多本经典的计算机书籍 PDF,包含 C 语言、C++、Java、Python、前端、数据库、操作系统、计算机网络、数据结构和算法、机器学习、编程人生 等,能够 star 一下,下次找书间接在下面搜寻,仓库继续更新中~

Github 地址

毛病

  • 对服务器内存耗费大
  • 存在提早,比方你每隔 3 分钟扫描一次,那最坏的延迟时间就是 3 分钟
  • 假如你的订单有几千万条,每隔几分钟这样扫描一次,数据库损耗极大

计划 2:JDK 的提早队列

思路

该计划是利用 JDK 自带的 DelayQueue 来实现,这是一个无界阻塞队列,该队列只有在提早期满的时候能力从中获取元素,放入 DelayQueue 中的对象,是必须实现 Delayed 接口的。

DelayedQueue 实现工作流程如下图所示

其中 Poll(): 获取并移除队列的超时元素,没有则返回空

take(): 获取并移除队列的超时元素,如果没有则 wait 以后线程,直到有元素满足超时条件,返回后果。

实现

定义一个类 OrderDelay 实现 Delayed,代码如下

package com.rjzheng.delay2;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class OrderDelay implements Delayed {

    private String orderId;

    private long timeout;

    OrderDelay(String orderId, long timeout) {
        this.orderId = orderId;
        this.timeout = timeout + System.nanoTime();}

    public int compareTo(Delayed other) {if (other == this) {return 0;}
        OrderDelay t = (OrderDelay) other;
        long d = (getDelay(TimeUnit.NANOSECONDS) - t.getDelay(TimeUnit.NANOSECONDS));
        return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
    }

    // 返回间隔你自定义的超时工夫还有多少
    public long getDelay(TimeUnit unit) {return unit.convert(timeout - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    void print() {System.out.println(orderId + "编号的订单要删除啦。。。。");
    }

}

运行的测试 Demo 为,咱们设定延迟时间为 3 秒

package com.rjzheng.delay2;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

public class DelayQueueDemo {public static void main(String[] args) {List<String> list = new ArrayList<String>();
        list.add("00000001");
        list.add("00000002");
        list.add("00000003");
        list.add("00000004");
        list.add("00000005");

        DelayQueue<OrderDelay> queue = newDelayQueue < OrderDelay > ();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5; i++) {
            // 提早三秒取出
            queue.put(new OrderDelay(list.get(i), TimeUnit.NANOSECONDS.convert(3, TimeUnit.SECONDS)));
            try {queue.take().print();
                System.out.println("After" + (System.currentTimeMillis() - start) + "MilliSeconds");
            } catch (InterruptedException e) {e.printStackTrace();
            }
        }
    }

}

输入如下

00000001 编号的订单要删除啦。。。。After 3003 MilliSeconds
00000002 编号的订单要删除啦。。。。After 6006 MilliSeconds
00000003 编号的订单要删除啦。。。。After 9006 MilliSeconds
00000004 编号的订单要删除啦。。。。After 12008 MilliSeconds
00000005 编号的订单要删除啦。。。。After 15009 MilliSeconds

能够看到都是提早 3 秒,订单被删除

长处

效率高, 工作触发时间延迟低。

毛病

  • 服务器重启后,数据全副隐没,怕宕机
  • 集群扩大相当麻烦
  • 因为内存条件限度的起因,比方下单未付款的订单数太多,那么很容易就呈现 OOM 异样
  • 代码复杂度较高

计划 3:工夫轮算法

思路

先上一张工夫轮的图(这图到处都是啦)

工夫轮算法能够类比于时钟,如上图箭头(指针)按某一个方向按固定频率轮动,每一次跳动称为一个 tick。这样能够看出定时轮由个 3 个重要的属性参数,ticksPerWheel(一轮的 tick 数),tickDuration(一个 tick 的持续时间)以及 timeUnit(工夫单位),例如当 ticksPerWheel=60,tickDuration=1,timeUnit= 秒,这就和事实中的始终的秒针走动齐全相似了。

如果以后指针指在 1 下面,我有一个工作须要 4 秒当前执行,那么这个执行的线程回调或者音讯将会被放在 5 上。那如果须要在 20 秒之后执行怎么办,因为这个环形构造槽数只到 8,如果要 20 秒,指针须要多转 2 圈。地位是在 2 圈之后的 5 下面(20 % 8 + 1)

实现

咱们用 Netty 的 HashedWheelTimer 来实现

给 Pom 加上上面的依赖

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.24.Final</version>
</dependency>

测试代码 HashedWheelTimerTest 如下所示

package com.rjzheng.delay3;

import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.Timer;
import io.netty.util.TimerTask;

import java.util.concurrent.TimeUnit;

public class HashedWheelTimerTest {

    static class MyTimerTask implements TimerTask {

        boolean flag;

        public MyTimerTask(boolean flag) {this.flag = flag;}

        public void run(Timeout timeout) throws Exception {System.out.println("要去数据库删除订单了。。。。");
            this.flag = false;
        }
    }

    public static void main(String[] argv) {MyTimerTask timerTask = new MyTimerTask(true);
        Timer timer = new HashedWheelTimer();
        timer.newTimeout(timerTask, 5, TimeUnit.SECONDS);
        int i = 1;
        while (timerTask.flag) {
            try {Thread.sleep(1000);
            } catch (InterruptedException e) {e.printStackTrace();
            }
            System.out.println(i + "秒过来了");
            i++;
        }
    }

}

输入如下

 1 秒过来了
2 秒过来了
3 秒过来了
4 秒过来了
5 秒过来了
要去数据库删除订单了。。。。6 秒过来了

长处

效率高, 工作触发时间延迟工夫比 delayQueue 低,代码复杂度比 delayQueue 低。

毛病

  • 服务器重启后,数据全副隐没,怕宕机
  • 集群扩大相当麻烦
  • 因为内存条件限度的起因,比方下单未付款的订单数太多,那么很容易就呈现 OOM 异样

计划 4:redis 缓存

思路一

利用 redis 的 zset,zset 是一个有序汇合,每一个元素 (member) 都关联了一个 score, 通过 score 排序来取汇合中的值

增加元素:ZADD key score member [score member …]

按程序查问元素:ZRANGE key start stop [WITHSCORES]

查问元素 score:ZSCORE key member

移除元素:ZREM key member [member …]

测试如下

增加单个元素
redis> ZADD page_rank 10 google.com
(integer) 1

增加多个元素
redis> ZADD page_rank 9 baidu.com 8 bing.com
(integer) 2

redis> ZRANGE page_rank 0 -1 WITHSCORES
1) "bing.com"
2) "8"
3) "baidu.com"
4) "9"
5) "google.com"
6) "10"

查问元素的 score 值
redis> ZSCORE page_rank bing.com
"8"

移除单个元素
redis> ZREM page_rank google.com
(integer) 1

redis> ZRANGE page_rank 0 -1 WITHSCORES
1) "bing.com"
2) "8"
3) "baidu.com"
4) "9"

那么如何实现呢?咱们将订单超时工夫戳与订单号别离设置为 score 和 member, 零碎扫描第一个元素判断是否超时,具体如下图所示

实现一

package com.rjzheng.delay4;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Tuple;

import java.util.Calendar;
import java.util.Set;

public class AppTest {

    private static final String ADDR = "127.0.0.1";

    private static final int PORT = 6379;

    private static JedisPool jedisPool = new JedisPool(ADDR, PORT);

    public static Jedis getJedis() {return jedisPool.getResource();
    }

    // 生产者, 生成 5 个订单放进去
    public void productionDelayMessage() {for (int i = 0; i < 5; i++) {
            // 提早 3 秒
            Calendar cal1 = Calendar.getInstance();
            cal1.add(Calendar.SECOND, 3);
            int second3later = (int) (cal1.getTimeInMillis() / 1000);
            AppTest.getJedis().zadd("OrderId", second3later, "OID0000001" + i);
            System.out.println(System.currentTimeMillis() + "ms:redis 生成了一个订单工作:订单 ID 为" + "OID0000001" + i);
        }
    }

    // 消费者,取订单

    public void consumerDelayMessage() {Jedis jedis = AppTest.getJedis();
        while (true) {Set<Tuple> items = jedis.zrangeWithScores("OrderId", 0, 1);
            if (items == null || items.isEmpty()) {System.out.println("以后没有期待的工作");
                try {Thread.sleep(500);
                } catch (InterruptedException e) {e.printStackTrace();
                }
                continue;
            }
            int score = (int) ((Tuple) items.toArray()[0]).getScore();
            Calendar cal = Calendar.getInstance();
            int nowSecond = (int) (cal.getTimeInMillis() / 1000);
            if (nowSecond >= score) {String orderId = ((Tuple) items.toArray()[0]).getElement();
                jedis.zrem("OrderId", orderId);
                System.out.println(System.currentTimeMillis() + "ms:redis 生产了一个工作:生产的订单 OrderId 为" + orderId);
            }
        }
    }

    public static void main(String[] args) {AppTest appTest = new AppTest();
        appTest.productionDelayMessage();
        appTest.consumerDelayMessage();}

}

此时对应输入如下

能够看到,简直都是 3 秒之后,生产订单。

然而,这一版存在一个致命的硬伤,在高并发条件下,多消费者会取到同一个订单号,咱们上测试代码 ThreadTest

package com.rjzheng.delay4;

import java.util.concurrent.CountDownLatch;

public class ThreadTest {

    private static final int threadNum = 10;
    private static CountDownLatch cdl = newCountDownLatch(threadNum);

    static class DelayMessage implements Runnable {public void run() {
            try {cdl.await();
            } catch (InterruptedException e) {e.printStackTrace();
            }
            AppTest appTest = new AppTest();
            appTest.consumerDelayMessage();}
    }

    public static void main(String[] args) {AppTest appTest = new AppTest();
        appTest.productionDelayMessage();
        for (int i = 0; i < threadNum; i++) {new Thread(new DelayMessage()).start();
            cdl.countDown();}
    }

}

输入如下所示

显然,呈现了多个线程生产同一个资源的状况。

解决方案

(1)用分布式锁,然而用分布式锁,性能降落了,该计划不细说。

(2)对 ZREM 的返回值进行判断,只有大于 0 的时候,才生产数据,于是将 consumerDelayMessage()办法里的

if(nowSecond >= score){String orderId = ((Tuple)items.toArray()[0]).getElement();
    jedis.zrem("OrderId", orderId);
    System.out.println(System.currentTimeMillis()+"ms:redis 生产了一个工作:生产的订单 OrderId 为"+orderId);
}

批改为

if (nowSecond >= score) {String orderId = ((Tuple) items.toArray()[0]).getElement();
    Long num = jedis.zrem("OrderId", orderId);
    if (num != null && num > 0) {System.out.println(System.currentTimeMillis() + "ms:redis 生产了一个工作:生产的订单 OrderId 为" + orderId);
    }
}

在这种批改后,从新运行 ThreadTest 类,发现输入失常了

思路二

该计划应用 redis 的 Keyspace Notifications,中文翻译就是键空间机制,就是利用该机制能够在 key 生效之后,提供一个回调,实际上是 redis 会给客户端发送一个音讯。是须要 redis 版本 2.8 以上。

实现二

在 redis.conf 中,退出一条配置

notify-keyspace-events Ex

运行代码如下

package com.rjzheng.delay5;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPubSub;

public class RedisTest {

    private static final String ADDR = "127.0.0.1";
    private static final int PORT = 6379;
    private static JedisPool jedis = new JedisPool(ADDR, PORT);
    private static RedisSub sub = new RedisSub();

    public static void init() {new Thread(new Runnable() {public void run() {jedis.getResource().subscribe(sub, "__keyevent@0__:expired");
            }
        }).start();}

    public static void main(String[] args) throws InterruptedException {init();
        for (int i = 0; i < 10; i++) {
            String orderId = "OID000000" + i;
            jedis.getResource().setex(orderId, 3, orderId);
            System.out.println(System.currentTimeMillis() + "ms:" + orderId + "订单生成");
        }
    }

    static class RedisSub extends JedisPubSub {
        @Override
        public void onMessage(String channel, String message) {System.out.println(System.currentTimeMillis() + "ms:" + message + "订单勾销");

        }
    }
}

输入如下

能够显著看到 3 秒过后,订单勾销了

ps:redis 的 pub/sub 机制存在一个硬伤,官网内容如下

原:Because Redis Pub/Sub is fire and forget currently there is no way to use this feature if your application demands reliable notification of events, that is, if your Pub/Sub client disconnects, and reconnects later, all the events delivered during the time the client was disconnected are lost.

翻: Redis 的公布 / 订阅目前是即发即弃 (fire and forget) 模式的,因而无奈实现事件的牢靠告诉。也就是说,如果公布 / 订阅的客户端断链之后又重连,则在客户端断链期间的所有事件都失落了。因而,计划二不是太举荐。当然,如果你对可靠性要求不高,能够应用。

长处

(1) 因为应用 Redis 作为音讯通道,音讯都存储在 Redis 中。如果发送程序或者工作处理程序挂了,重启之后,还有重新处理数据的可能性。

(2) 做集群扩大相当不便

(3) 工夫准确度高

毛病

须要额定进行 redis 保护

计划 5:应用音讯队列

思路

咱们能够采纳 rabbitMQ 的延时队列。RabbitMQ 具备以下两个个性,能够实现提早队列

RabbitMQ 能够针对 Queue 和 Message 设置 x-message-tt,来管制音讯的生存工夫,如果超时,则音讯变为 dead letter

lRabbitMQ 的 Queue 能够配置 x-dead-letter-exchange 和 x-dead-letter-routing-key(可选)两个参数,用来管制队列内呈现了 deadletter,则依照这两个参数从新路由。联合以上两个个性,就能够模拟出提早音讯的性能, 具体的,我改天再写一篇文章,这里再讲下去,篇幅太长。

长处

高效, 能够利用 rabbitmq 的分布式个性轻易的进行横向扩大, 音讯反对长久化减少了可靠性。

毛病

自身的易用度要依赖于 rabbitMq 的运维. 因为要援用 rabbitMq, 所以复杂度和老本变高。

–end–

最初给大家分享一个 Github 仓库,下面有大彬整顿的 300 多本经典的计算机书籍 PDF,包含 C 语言、C++、Java、Python、前端、数据库、操作系统、计算机网络、数据结构和算法、机器学习、编程人生 等,能够 star 一下,下次找书间接在下面搜寻,仓库继续更新中~

Github 地址:https://github.com/Tyson0314/java-books

正文完
 0