php实现防止重复提交

分类: 源代码 > PHP

/**

 * @desc 防止请求并发性重复提交限制

 * @access public

 * @author jiangguibin

 * @date 2018-01-04

 * @return bool

 */

function setConcurrentLimit($key = null, $expire_time = 10) {

    // 程序关闭时执行该函数

    static $registerShutdownFunction = false;

    if ($registerShutdownFunction === false) {

        register_shutdown_function(array('ZGeneral', 'setConcurrentLimit'));

        $registerShutdownFunction = true;

    }

    static $cacheKey = array();

    $redis = new redis()

    // 如果缓存key为null,则清除缓存key

    if ($key === null) {

        foreach ($cacheKey as $k) {

            $redis->remove($k);

        }

        return true;

    }

    // 设置缓存key

    $key = md5('wallet_setConcurrentLimit_' . $key);

    $cacheKey[] = $key;

    $current_time = time();

    // 给定的key不存在时,返回true

    if ($redis->setnx($key, $current_time)) {

        $redis->setTimeout($key, $expire_time);

        return true;

    } else {

        $cache_time = $redis->get($key);

        if ($cache_time && ($current_time - $cache_time >= $expire_time)) {

            $redis->remove($key);

            return true;

        }

    }

    return false;

来源:原创 发布时间:2020-07-04 22:39:12