$prefix = ‘DS’; //标题前缀
$currentCycle = date(‘ymd‘); // 日期拼接成中间
$key = "codegen:{$currentCycle}:{$prefix}";
$Redis = $this->Redis->getRedis(); // 连接redis
$codeNum = $Redis->incr($key);
// 第一条,设置有效期,删除过期key
if ($codeNum == 1) {
$dateCycle = in_array($type, self::$_shortCode) ? ‘month‘ : ‘day‘ ;
$timeFormat = in_array($type, self::$_shortCode) ? ‘Y-m-01 00:00:00‘ : ‘Y-m-d 00:00:00‘ ;
// 设置有效期
$expireAt = strtotime(date($timeFormat , strtotime("+1 {$dateCycle}")));
$Redis->expireAt($key, $expireAt);
// 删除过期key,加锁,一周期只删一次
if ($Redis->setnx("codegen:{$currentCycle}:rmLock", 1)) {
$lastCycle = date($dateFormat, strtotime("-1 $dateCycle"));
$keys = $Redis->keys("codegen:{$lastCycle}:*");
foreach ($keys as $k) {
$Redis->del($k);
}
}
}
if (in_array($type, self::$_shortCode)) {
// 短编号
$codeNum = $codeNum < 10 ? str_pad($codeNum, 2, ‘0‘, STR_PAD_LEFT) : $codeNum;
} else {
$codeNum = str_pad($codeNum, 4, ‘0‘, STR_PAD_LEFT);
}
return $prefix . $codeNum;