考虑到sql server以及c#,最多只能用decimal类型,也就是29位的数字,做了下面这个数字型id生成器:
class Program { static void Main(string[] args) { int i = 100000; Timing t = new Timing(); t.Start(); while(i-->0) UniqueIdGenerator.Next(); t.Stop(); t.Display(""); } } public static class UniqueIdGeneratorHelper { public static long IP2Long(String strIP) { long[] ip = new long[4]; string[] s = strIP.Split('.'); ip[0] = long.Parse(s[0]); ip[1] = long.Parse(s[1]); ip[2] = long.Parse(s[2]); ip[3] = long.Parse(s[3]); return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3]; } } public static class UniqueIdGenerator { static UniqueIdGenerator() { ip = UniqueIdGeneratorHelper.IP2Long("192.168.1.21");//需要自己从配置文件中读取 } private static long ip=0; public static decimal Next() { return decimal.Parse(DateTime.Now.ToString("yyyyMMddHHmmssff") + ip.ToString() + GetSequence().ToString()); } private static int curSeq = 1; private static object o = 1; private static int GetSequence() { lock (o) { if (curSeq > 999) curSeq = 1; return curSeq++; } } }
十万次请求,花了半秒不到,应该还行。