有这样一个场景,有多台终端,要获取唯一的流水号,流水号格式是 日期+0001形式,使用MySQL的存储过程+全局锁实现这个需求。
以下是代码示例。
注:所有的终端连接到MySQL服务器获取流水号,如果获取到的是 "-1",需要重新获取。
sql
CREATE DEFINER = 'root'@'%'
PROCEDURE GetCurrentDateNumber()
BEGIN
set @lock_string='order_num_lock';
#5代表获取锁时等待5秒
SELECT GET_LOCK(@lock_string,5) INTO @order_num_lock;
set @TodayString=DATE_FORMAT(CURDATE(),'%Y%m%d');
IF @order_num_lock=1 THEN
SELECT COUNT(*) INTO @TodayCount
FROM OrderInfo WHERE LEFT(OrderNum,8)=@TodayString;
IF @TodayCount=0 THEN
set @SerialNum=CONCAT(@TodayString,'0001');
INSERT INTO OrderInfo (OrderNum) VALUE (@SerialNum);
select @SerialNum SerialNum;
ELSE
SELECT MAX(OrderNum) INTO @MaxOrderNum
FROM OrderInfo WHERE LEFT(OrderNum,8)=@TodayString;
set @SerialNumInt=cast(RIGHT(@MaxOrderNum,4) AS SIGNED)+1;
SET @SerialNum=CONCAT(@TodayString,RIGHT(CONCAT('0000',CAST(@SerialNumInt AS char)),4));
INSERT INTO OrderInfo (OrderNum) VALUE (@SerialNum);
select @SerialNum SerialNum;
END IF;
select RELEASE_LOCK(@lock_string) INTO @RELEASE_LOCK;
ELSE
SELECT '-1' SerialNum; #拿不到锁时,返回-1
END IF;
END