In the development process, often use a sequence number, such as order number, here describes two methods, one is generated Redis, one is Sql
A, Redis SEQ ID generated examples
public string GetFileName() { var nextDay = DateTime.Now.AddDays(1); var dueTime = new DateTime(nextDay.Year, nextDay.Month, nextDay.Day, 0, 0, 0).Subtract(DateTime.Now);//第二天凌晨过期 var IncomeNumber = RedisCacheHelper.Instance.GetIncrValue(PictureLibraryConsts.FileNameKey, 1, true, dueTime); var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + IncomeNumber.ToString().PadLeft(8, '0'); return fileName; }
Wherein RedisCacheHelper.Instance.GetIncrValue follows:
/// <Summary> /// atomic value retrieved from key according /// </ Summary> /// <param name = "key"> increment the key </ param> /// <param name = "key"> value increment of </ param> /// <param name = "autoRemoveKey"> whether to automatically delete </ param> /// <param name = "expireTime"> delete key expiration time </ param> /// <Returns> </ Returns> public Long GetIncrValue ( String Key, Long value = . 1 , BOOL autoRemoveKey = to true ,TimeSpan expireTime = default(The TimeSpan)) { IF ( String .IsNullOrEmpty (Key)) the throw new new Exception ( " Key blank " ); the try { var IncreaseValue = redisClient.Increment (Key, value); // first time acquired, and automatically deleted Key IF (IncreaseValue == . 1 && autoRemoveKey) { var _expireTime expireTime == = default (the TimeSpan) TimeSpan.FromDays (? 2 ): expireTime; // default time is 2 days SetExpireTime (key, _expireTime); } return increaseValue; } catch (Exception ex) { throw ex; } }
Second, SQL generated using the sequence number (network from Mu class)
sql paper using the mysql
First, build a table as follows:
New then stored as follows:
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateOrderNo`() BEGIN DECLARE v_cnt INT; DECLARE v_timestr INT; DECLARE rowcount BIGINT; set v_timestr=DATE_FORMAT(now(),'%Y%m%d'); select ROUND(rand()*100,0)+1 into v_cnt; start TRANSACTION; update order_seq set order_sn=order_sn+v_cnt where timestr=v_timestr; if row_count()=0 then insert into order_seq(timestr,order_sn)VALUES(v_timestr,v_cnt); end if; select CONCAT(v_timestr,LPAD(order_sn,7,0)) as order_sn from order_seq where timestr=v_timestr; COMMIT; END