当前位置:实例文章 » C#开发实例» [文章]C# 版 雪花ID

C# 版 雪花ID

发布人:shili8 发布时间:2024-02-11 18:47 阅读次数:88

在分布式系统中,生成唯一的ID是非常重要的。雪花算法是一种生成全局唯一ID的算法,它可以在分布式系统中生成唯一的ID,避免重复。

下面是一个C#版本的雪花ID生成器的示例代码:

csharpusing System;

public class SnowflakeIdGenerator{
 private const long Twepoch =1288834974657L;
 private const int WorkerIdBits =5;
 private const int DatacenterIdBits =5;
 private const int SequenceBits =12;

 private const long MaxWorkerId = -1L ^ (-1L << WorkerIdBits);
 private const long MaxDatacenterId = -1L ^ (-1L << DatacenterIdBits);

 private const int WorkerIdShift = SequenceBits;
 private const int DatacenterIdShift = SequenceBits + WorkerIdBits;
 private const int TimestampLeftShift = SequenceBits + WorkerIdBits + DatacenterIdBits;
 private const long SequenceMask = -1L ^ (-1L << SequenceBits);

 private readonly object _lock = new object();

 private long _lastTimestamp = -1L;
 private long _sequence =0L;

 public long WorkerId { get; }
 public long DatacenterId { get; }

 public SnowflakeIdGenerator(long workerId, long datacenterId)
 {
 if (workerId > MaxWorkerId || workerId <0)
 {
 throw new ArgumentException($"Worker ID must be between0 and {MaxWorkerId}");
 }

 if (datacenterId > MaxDatacenterId || datacenterId <0)
 {
 throw new ArgumentException($"Datacenter ID must be between0 and {MaxDatacenterId}");
 }

 WorkerId = workerId;
 DatacenterId = datacenterId;
 }

 public long NextId()
 {
 lock (_lock)
 {
 long timestamp = GetCurrentTimestamp();

 if (timestamp < _lastTimestamp)
 {
 throw new Exception("Clock moved backwards. Refusing to generate ID");
 }

 if (timestamp == _lastTimestamp)
 {
 _sequence = (_sequence +1) & SequenceMask;
 if (_sequence ==0)
 {
 timestamp = WaitNextMillis(timestamp);
 }
 }
 else {
 _sequence =0;
 }

 _lastTimestamp = timestamp;

 return ((timestamp - Twepoch) << TimestampLeftShift)
 | (DatacenterId << DatacenterIdShift)
 | (WorkerId << WorkerIdShift)
 | _sequence;
 }
 }

 private long GetCurrentTimestamp()
 {
 return (long)(DateTime.UtcNow - new DateTime(1970,1,1)).TotalMilliseconds;
 }

 private long WaitNextMillis(long lastTimestamp)
 {
 long timestamp = GetCurrentTimestamp();
 while (timestamp <= lastTimestamp)
 {
 timestamp = GetCurrentTimestamp();
 }
 return timestamp;
 }
}


在上面的代码中,我们定义了一个SnowflakeIdGenerator类,它包含了生成雪花ID的逻辑。我们可以通过调用NextId方法来获取一个唯一的ID。

使用示例:

csharpvar generator = new SnowflakeIdGenerator(1,1);
var id = generator.NextId();
Console.WriteLine($"Generated ID: {id}");


通过使用这个C#版本的雪花ID生成器,我们可以在分布式系统中生成唯一的ID,确保数据的唯一性和一致性。

相关标签:c#java开发语言
其他信息

其他资源

Top