烦恼的唯一订单号= =、借助于redis锁
/** * @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,转载请注明出处
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。