zoukankan      html  css  js  c++  java
  • 生成数据库自增不重复ID的方法

    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                var list = new HashSet<string>(101);
                for (int i = 0; i < 100; i++)
                {
                    var task = Task.Factory.StartNew((m =>
                    {
                        var id = McidGenerator.NewMcid();
                        list.Add(id);
                        Console.WriteLine($"序号:{(int)m + 1}  线程ID:{Thread.CurrentThread.ManagedThreadId} 生成的MCID:{id}");
                    }), i);
                }
                Thread.Sleep(10000);
                var n = 1;
                foreach (var li in list.OrderBy(i=>i))
                {
                    
                    Console.WriteLine($"序号:{(int)n + 1} 生成的MCID:{li}");
                    n++;
                }
                Console.ReadLine();
            }
        }
    
        public static class McidGenerator
        {
            private const int MaxId = 9;
            private static bool _allNew = true;
            private static int _incrementId = 0;
            private static DateTimeOffset _current = DateTimeOffset.Now;
            private static readonly object SequenceLock = new object();
    
            public static string NewMcid()
            {
                lock (SequenceLock)
                {
                    var now = DateTimeOffset.Now;
                    if (_allNew)
                    {
                        _allNew = false;
                        _current = now;
                        return now.ToString("yyyyMMddHHmmssfffff") + _incrementId;
                    }
    
                    if (Convert.ToDateTime(_current.ToString("yyyy-MM-dd HH:mm:ss.fffff")) == Convert.ToDateTime(now.ToString("yyyy-MM-dd HH:mm:ss.fffff")))
                    {
                        _incrementId++;
                        _current = now;
                        return now.ToString("yyyyMMddHHmmssfffff") + _incrementId;
                    }
    
                    _incrementId++;
                    _incrementId = _incrementId > MaxId ? 0 : _incrementId;
                    _current = now;
                    return now.ToString("yyyyMMddHHmmssfffff") + _incrementId;
                }
            }
        }
    }
  • 相关阅读:
    APP测试之找密码
    测试理论
    LR性能测试
    Linux 操作系统常用命令
    C#后台HttpWebRequest代码调用WebService
    Python3在Windows下安装虚拟环境
    oracle使用rownum进行分页查询
    oracle over结合row_number分区进行数据去重处理
    Oracle实现主键自动增长
    Asp.net WebApi调用
  • 原文地址:https://www.cnblogs.com/hanstar/p/9901968.html
Copyright © 2011-2022 走看看