1、方法一:
//20位的订单号,时间戳+随机数,时间戳是精确到微妙的时间戳,然后加3位随机数。
function getOrderNo(){
$houseNum = time()-strtotime(date('Y-m-d',time()));
$time = date('ymd');
$length = 20;
$prefixTime = $time.$houseNum;
$lastLen = $length - strlen($prefixTime);
$utimestamp = microtime(true);
$timestamp = floor($utimestamp);
$milliseconds = round(($utimestamp - $timestamp) * 1000000);
$orderNo = $prefixTime.$milliseconds;
if($lastLen-strlen($milliseconds)>0){
for($i=0;$i
$orderNo .= rand(1,9);
}
}
return $orderNo;
}
方法二:
//时间戳+redis生成的唯一数字
//18位的订单号,时间戳是精确到秒的,redis的key是秒级为单位的,在同一秒中,随着请求数在递增,是不会重复的。然后确定位数,补0;
function getOrderNo(){
$houseNum = time()-strtotime(date('Y-m-d',time()));
$time = date('ymd');
$length = 18;//默认18位
$prefixTime = $time.$houseNum;
$lastLen = $length - strlen($prefixTime);
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);
$reqNoKey = 'OrderNoKey:'.date('YmdHis'); // 设置redis键值,每秒钟的请求次数
$reqNo = $redis->incr($reqNoKey); // 将redis值加1
$redis->expire($reqNoKey, 5); // 设置redis过期时间,避免垃圾数据过多
if($lastLen-strlen($reqNo)>0){
for($i=0;$i
$prefixTime .= '0';
}
}
$orderNo = $prefixTime.$reqNo;
return $orderNo;
}