首页 > 其他 > 详细

基于redis 生成唯一订单号

时间:2021-07-30 22:57:36      阅读:34      评论:0      收藏:0      [点我收藏+]

烦恼的唯一订单号= =、借助于redis锁

定义场景:laravel  php

/**
     * @param string $key redisKey
     * @param int $length 字符串长度
     * @param string $prefix 字符串前缀
     * @param bool $useEn 是否可用英文
     * @return string
     */
    function get_unique_order_no(string $key, int $length, string $prefix = ‘‘, bool $useEn = false): string
    {
        $key = $key . ‘_‘ . date(‘Ymd‘);
        $redis = Redis::connection();
        $redisLock = new \Illuminate\Cache\RedisLock($redis, $key . ‘_lock‘, 30);
        try {
            $redisNum = $redisLock->block(5, function () use ($key) {
                if (Redis::ttl($key) < 0) {
                    $time = strtotime(date("Y-m-d", time())) + 60 * 60 * 24 - strtotime(date("Y-m-d H:i:s", time()));
                    Redis::expire($key, $time);
                }
                Redis::incr($key);
                return Redis::get($key);
            });
            $string = $prefix . date(‘ymdHi‘);
            if ($useEn) {
                $redisNum = dechex($redisNum);
            } else {
                $redisNum = decoct($redisNum);
            }
            $len = $length - strlen($redisNum);
            $leftStrLen = $len - strlen($string);
            if ($leftStrLen >= 0) {
                $string = str_pad($string, $len, 0, STR_PAD_RIGHT);
            } else {
                $string = substr($string, 0, $len);
            }
            return $string . $redisNum;
        } catch (\Throwable $e) {
            return substr($prefix . date(‘ymd‘) . hexdec(uniqid()), 0, $length);
        }
    }

  代码暂时解决了我的问题,后面有情况再做调整

  博客唯一地址:https://www.cnblogs.com/pfdltutu/p/15080887.html,转载请注明出处

基于redis 生成唯一订单号

原文:https://www.cnblogs.com/pfdltutu/p/15080887.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!