生成序列號

在開發過程當中常常要用到序列號,好比訂單號,這裏介紹兩種方法,一種是Redis生成,一種是Sqlmysql

1、Redis生成序列號例子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方法以下:sql

 /// <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;
            }
        }

2、利用SQL生成序列號(來自慕課網)spa

本文的sql用的是mysqlcode

首先建一張表以下:blog

而後新建存儲過程以下:開發

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
相關文章
相關標籤/搜索