订单号生成办法

1、Redis Incr

    public class RedisConnection
    {
        private static readonly ConfigurationOptions ConfigurationOptions = ConfigurationOptions.Parse("127.0.0.1" + ":" + "6379");
        private static ConnectionMultiplexer _redisConn;
        private static readonly object Locker = new object();
        private RedisConnection() { }  

        /// <summary>
        /// 单例获取Redis链接
        /// </summary>
        public static ConnectionMultiplexer GetRedisConn
        {
            get
            {
                if (_redisConn == null)
                {
                    lock (Locker)
                    {
                        if (_redisConn == null || !_redisConn.IsConnected)
                        {
                            _redisConn = ConnectionMultiplexer.Connect(ConfigurationOptions);
                        }
                    }
                }
                return _redisConn;
            }
        }
    }

  

        /// <summary>
        /// 生成规则:时间+redis自增
        /// 缺点:可以根据redis自增知道订单量
        /// </summary>
        public static string CreateByRedis()
        {
            //Redis服务器链接失败会报异常
            try
            {
                //单例获取Redis链接
                var redis = RedisConnection.GetRedisConn;
                var db = redis.GetDatabase();
                //根据当前日期获取Redis订单号自增的key
                var incrkey = "Incr_" + DateTime.Now.ToString("yyyyMMdd");
                if (!db.KeyExists(incrkey))
                {
                    db.StringSet(incrkey, 1, new TimeSpan(24, 0, 0));
                }

                var orderDateTime = DateTime.Now.ToString("yyMMdd"); //因为我们的Redis Incr是按照天数来的 所以原则上用天的区分就好了
                var orderIncr = db.StringIncrement(incrkey).ToString("0000000");
                return orderDateTime + orderIncr;
            }
            catch (Exception)
            {
                //TODO 这里可以写个日志
                return "";
            } 
        }

  

posted @ 2017-05-19 12:01  上古时期的码农  阅读(609)  评论(0编辑  收藏  举报