在开发过程中经常要用到序列号,比如订单号,这里介绍两种方法,一种是Redis生成,一种是Sql
一、Redis生成序列号例子
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; }
其中RedisCacheHelper.Instance.GetIncrValue方法如下:
/// <summary> /// 根据原子性获取key的自增值 /// </summary> /// <param name="key">自增的key</param> /// <param name="key">自增的value</param> /// <param name="autoRemoveKey">是否自动删除</param> /// <param name="expireTime">删除key的过期时间</param> /// <returns></returns> public long GetIncrValue(string key, long value = 1, bool autoRemoveKey = true, TimeSpan expireTime = default(TimeSpan)) { if (string.IsNullOrEmpty(key)) throw new Exception("key为空"); try { var increaseValue = redisClient.Increment(key, value); //第一次获取时,并且自动删除Key if (increaseValue == 1 && autoRemoveKey) { var _expireTime = expireTime == default(TimeSpan) ? TimeSpan.FromDays(2) : expireTime;//默认时间为2天 SetExpireTime(key, _expireTime); } return increaseValue; } catch (Exception ex) { throw ex; } }
二、利用SQL生成序列号(来自慕课网)
本文的sql用的是mysql
首先建一张表如下:
然后新建存储过程如下:
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