zoukankan      html  css  js  c++  java
  • 基于redis 生成唯一订单号

    烦恼的唯一订单号= =、借助于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 IlluminateCacheRedisLock($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,转载请注明出处

  • 相关阅读:
    Chaos网络库(一) 开篇介绍
    对Oracle中的表进行分区
    java socket编程
    SQL优化
    冒泡排序、选择排序和插入
    集合有趣的地方
    java中String s = new String("abc")创建了几个对象
    集合排序
    接口与抽象类的区别
    软件测试流程
  • 原文地址:https://www.cnblogs.com/pfdltutu/p/15080887.html
Copyright © 2011-2022 走看看