生成主键Id,字符串自增,插入查询高性能
原理采用 时间戳字符串 + 变量字符串 组成一个唯一字符串
1 using System; 2 using System.Collections.Generic; 3 using System.Diagnostics; 4 using System.Threading; 5 using System.Threading.Tasks; 6 7 namespace ConsoleApp2 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 Console.WriteLine("task start!"); 14 15 var dic = new Dictionary<string, string>(100000); 16 17 for (int o = 0; o < 100; o++) 18 { 19 var task = Task.Factory.StartNew((m => 20 { 21 for (var i = 10000; i > 0; i--) 22 { 23 var id = Mcid.NewMcid(); 24 dic.Add(id, ""); 25 Console.WriteLine(id); 26 } 27 }), o); 28 } 29 30 31 Thread.Sleep(1000000); 32 Console.ReadLine(); 33 } 34 35 36 } 37 38 public class Mcid 39 { 40 private const int MaxId = 999;//确保Millisecond级生成速度来设置最大值,这里每毫秒最多产生1000个id// 41 private const int MinId = 0; 42 private static bool _new = true; 43 private static int _incrementId = MinId; 44 private static DateTime _origin = new DateTime(2019, 1, 1); 45 private static long _current = (long)(DateTime.UtcNow - _origin).TotalMilliseconds; 46 private static readonly object _lock = new object(); 47 48 public static string NewMcid(string prefix = "") 49 { 50 lock (_lock) 51 { 52 if (_new) 53 { 54 _new = false; 55 return $"{prefix}{_current}{_incrementId.ToString($"D{MaxId.ToString().Length}")}"; 56 } 57 var timeStamp = (long)(DateTime.UtcNow - _origin).TotalMilliseconds; 58 if (_current == timeStamp) 59 { 60 _incrementId++; 61 if (_incrementId > MaxId)//考虑用Thread.Sleep(1),这里会在99停几毫秒时间,求更好的方式 62 { 63 return Loop(prefix); 64 } 65 return $"{prefix}{_current}{_incrementId.ToString().PadLeft(MaxId.ToString().Length, '0')}"; 66 } 67 68 _incrementId = MinId; 69 _current = timeStamp; 70 return $"{prefix}{_current}{_incrementId.ToString().PadLeft(MaxId.ToString().Length, '0')}"; 71 } 72 } 73 74 private static string Loop(string prefix) 75 { 76 Thread.Sleep(1); 77 var timeStamp = (long)(DateTime.UtcNow - _origin).TotalMilliseconds; 78 if (_current == timeStamp) 79 { 80 return Loop(prefix); 81 } 82 83 _incrementId = MinId; 84 _current = timeStamp; 85 return $"{prefix}{_current}{_incrementId.ToString().PadLeft(MaxId.ToString().Length, '0')}"; 86 } 87 88 } 89 }
有更好的想法望指正