生成唯一long类型自增Id:
using System; namespace ConsoleApp1 { public static class Snowflake { static SnowflakeTool idworker = new SnowflakeTool(1); public static long Next() { return idworker.nextId(); } } public class SnowflakeTool { //机器ID private static long nodeId; private static long twepoch = 687888001020L; //唯一时间,这是一个避免重复的随机量,自行设定不要大于当前时间戳 private static long sequence = 0L; private static int workerIdBits = 4; //机器码字节数。4个字节用来保存机器码(定义为Long类型会出现,最大偏移64位,所以左移64位没有意义) public static long maxWorkerId = -1L ^ -1L << workerIdBits; //最大机器ID private static int sequenceBits = 10; //计数器字节数,10个字节用来保存计数码 private static int workerIdShift = sequenceBits; //机器码数据左移位数,就是后面计数器占用的位数 private static int timestampLeftShift = sequenceBits + workerIdBits; //时间戳左移动位数就是机器码和计数器总字节数 public static long sequenceMask = -1L ^ -1L << sequenceBits; //一微秒内可以产生计数,如果达到该值则等到下一微妙在进行生成 private long lastTimestamp = -1L; /// <summary> /// 机器码 /// </summary> /// <param name="workerId"></param> public SnowflakeTool(long workerId) { if (workerId > maxWorkerId || workerId < 0) throw new Exception(string.Format("节点id 不能大于 {0} 或者 小于 0 ", workerId)); SnowflakeTool.nodeId = workerId; } public long nextId() { lock (this) { long timestamp = timeGen(); if (this.lastTimestamp == timestamp) { //同一微妙中生成ID SnowflakeTool.sequence = (SnowflakeTool.sequence + 1) & SnowflakeTool.sequenceMask; //用&运算计算该微秒内产生的计数是否已经到达上限 if (SnowflakeTool.sequence == 0) { //一微妙内产生的ID计数已达上限,等待下一微妙 timestamp = tillNextMillis(this.lastTimestamp); } } else { //不同微秒生成ID SnowflakeTool.sequence = 0; //计数清0 } if (timestamp < lastTimestamp) { //如果当前时间戳比上一次生成ID时时间戳还小,抛出异常,因为不能保证现在生成的ID之前没有生成过 throw new Exception(string.Format("Clock moved backwards. Refusing to generate id for {0} milliseconds", this.lastTimestamp - timestamp)); } this.lastTimestamp = timestamp; //把当前时间戳保存为最后生成ID的时间戳 long nextId = (timestamp - twepoch << timestampLeftShift) | SnowflakeTool.nodeId << SnowflakeTool.workerIdShift | SnowflakeTool.sequence; return nextId; } } /// <summary> /// 获取下一微秒时间戳 /// </summary> /// <param name="lastTimestamp"></param> /// <returns></returns> private long tillNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } /// <summary> /// 生成当前时间戳 /// </summary> /// <returns></returns> private long timeGen() { return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds; } } }
调用 校验重复:
var list = new List<long>(); for (int i = 0; i < 100000; i++) { var id = Snowflake.Next();// 通过雪花算法 Console.WriteLine(id); } //校验重复 Console.WriteLine("--------------------------------------"); Console.WriteLine(list.Distinct().Count()); Console.WriteLine("--------------------------------------"); var list2 = list.GroupBy(x => x).Where(x => x.Count() > 1); foreach (var item in list2) { Console.WriteLine(item.Key); } Console.ReadKey();
long类型序列化精度丢失的处理:
[JsonConverter(typeof(MyNumberConverter), NumberConverterShip.Int64)] public long GoodsId { set; get; }
MyNumberConverter,NumberConverterShip:
using Newtonsoft.Json; using System; using System.ComponentModel; using System.Linq; namespace Seckill.EntityFrameworkCore.Converter { /// <inheritdoc /> /// <summary> /// 大数据json序列化重写 /// </summary> public sealed class MyNumberConverter : JsonConverter { /// <summary> /// 转换成字符串的类型 /// </summary> private readonly NumberConverterShip _ship; /// <summary> /// 大数据json序列化重写实例化 /// </summary> public MyNumberConverter() { _ship = (NumberConverterShip)0xFF; } /// <summary> /// 大数据json序列化重写实例化 /// </summary> /// <param name="ship">转换成字符串的类型</param> public MyNumberConverter(NumberConverterShip ship) { _ship = ship; } /// <inheritdoc /> /// <summary> /// 确定此实例是否可以转换指定的对象类型。 /// </summary> /// <param name="objectType">对象的类型。</param> /// <returns>如果此实例可以转换指定的对象类型,则为:<c>true</c>,否则为:<c>false</c></returns> public override bool CanConvert(Type objectType) { var typecode = Type.GetTypeCode(objectType.Name.Equals("Nullable`1") ? objectType.GetGenericArguments().First() : objectType); switch (typecode) { case TypeCode.Decimal: return (_ship & NumberConverterShip.Decimal) == NumberConverterShip.Decimal; case TypeCode.Double: return (_ship & NumberConverterShip.Double) == NumberConverterShip.Double; case TypeCode.Int64: return (_ship & NumberConverterShip.Int64) == NumberConverterShip.Int64; case TypeCode.UInt64: return (_ship & NumberConverterShip.UInt64) == NumberConverterShip.UInt64; case TypeCode.Single: return (_ship & NumberConverterShip.Single) == NumberConverterShip.Single; default: return false; } } /// <inheritdoc /> /// <summary> /// 读取对象的JSON表示。 /// </summary> /// <param name="reader">从 <see cref="T:Newtonsoft.Json.JsonReader" /> 中读取。</param> /// <param name="objectType">对象的类型。</param> /// <param name="existingValue">正在读取的对象的现有值。</param> /// <param name="serializer">调用的序列化器实例。</param> /// <returns>对象值。</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return AsType(reader.Value.ToString(), objectType); } /// <summary> /// 字符串格式数据转其他类型数据 /// </summary> /// <param name="input">输入的字符串</param> /// <param name="destinationType">目标格式</param> /// <returns>转换结果</returns> public static object AsType(string input, Type destinationType) { try { var converter = TypeDescriptor.GetConverter(destinationType); if (converter.CanConvertFrom(typeof(string))) { return converter.ConvertFrom(null, null, input); } converter = TypeDescriptor.GetConverter(typeof(string)); if (converter.CanConvertTo(destinationType)) { return converter.ConvertTo(null, null, input, destinationType); } } catch { return null; } return null; } /// <inheritdoc /> /// <summary> /// 写入对象的JSON表示形式。 /// </summary> /// <param name="writer">要写入的 <see cref="T:Newtonsoft.Json.JsonWriter" /> 。</param> /// <param name="value">要写入对象值</param> /// <param name="serializer">调用的序列化器实例。</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { writer.WriteNull(); } else { var objectType = value.GetType(); var typeCode = Type.GetTypeCode(objectType.Name.Equals("Nullable`1") ? objectType.GetGenericArguments().First() : objectType); switch (typeCode) { case TypeCode.Decimal: writer.WriteValue(((decimal)value).ToString("f6")); break; case TypeCode.Double: writer.WriteValue(((double)value).ToString("f4")); break; case TypeCode.Single: writer.WriteValue(((float)value).ToString("f2")); break; default: writer.WriteValue(value.ToString()); break; } } } } /// <summary> /// 转换成字符串的类型 /// </summary> [Flags] public enum NumberConverterShip { /// <summary> /// 长整数 /// </summary> Int64 = 1, /// <summary> /// 无符号长整数 /// </summary> UInt64 = 2, /// <summary> /// 浮点数 /// </summary> Single = 4, /// <summary> /// 双精度浮点数 /// </summary> Double = 8, /// <summary> /// 大数字 /// </summary> Decimal = 16 } }