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