有这样一个场景,有多台终端,要获取唯一的流水号,流水号格式是 日期+0001形式,使用MySQL的存储过程+全局锁实现这个需求。
以下是代码示例。
注:所有的终端连接到MySQL服务器获取流水号,如果获取到的是 “-1”,需要重新获取。
CREATE DEFINER = 'root'@'%'
PROCEDURE GetCurrentDateNumber()
BEGINset @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 THENSELECT COUNT(*) INTO @TodayCountFROM OrderInfo WHERE LEFT(OrderNum,8)=@TodayString;IF @TodayCount=0 THENset @SerialNum=CONCAT(@TodayString,'0001');INSERT INTO OrderInfo (OrderNum) VALUE (@SerialNum);select @SerialNum SerialNum;ELSESELECT MAX(OrderNum) INTO @MaxOrderNumFROM 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;ELSESELECT '-1' SerialNum; #拿不到锁时,返回-1END IF;END