Home  >  Article  >  php教程  >  利用Redis生成订单号

利用Redis生成订单号

PHP中文网
PHP中文网Original
2016-05-23 16:40:132687browse

php代码

class Pay extends Web
{
    /**
     * 最多以每秒999个的速度生成13位订单号
     *
     * @return string
     */
    function getOrderId()
    {
        //哪年,哪天,哪一秒
        $base = date('y') . date('z') . str_pad((date('H') * 60 * 60 + date('i') * 60 + date('s')), 5, 0, STR_PAD_LEFT);
        $next_sec = time() + 1;

        $pre_max_id = 999;
        while(time() < $next_sec) {
            $order_id = mt_rand(1, $pre_max_id);

            $store_key = parent::getCacheKey(&#39;orderIdCache&#39;, $base, $order_id);
            $setRet = $this->store->setnx($store_key, 1);

            if ($setRet) {
                $this->store->expire($store_key, 5);
                return $base.str_pad($order_id, 3, 0, STR_PAD_LEFT);
            } else {
                continue;
            }
        }

        return $this->getOrderId();
    }
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn