using System; namespace ZC { /// /// id生成器,当前使用的是时间戳作为id生成器的唯一id /// public static class IDGenerator { // private static long lastTimestamp = -1L; private static long sequence = 0L; private static readonly long twepoch = 1288834974657L; // Twitter Snowflake算法中的自定义起始时间 private static readonly long machineId = 1L; // 机器码,可以自定义 public static long Generate() { long timestamp = TimeGen(); if (lastTimestamp == timestamp) { sequence = (sequence + 1) & 4095L; if (sequence == 0) { timestamp = TilNextMillis(lastTimestamp); } } else { sequence = 0L; } lastTimestamp = timestamp; return (timestamp - twepoch) << 22 | machineId << 12 | sequence; } private static long TilNextMillis(long lastTimestamp) { long timestamp = TimeGen(); while (timestamp <= lastTimestamp) { timestamp = TimeGen(); } return timestamp; } private static long TimeGen() { return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds; } } }