RuoVea.ExIdGen
10.0.0.1
dotnet add package RuoVea.ExIdGen --version 10.0.0.1
NuGet\Install-Package RuoVea.ExIdGen -Version 10.0.0.1
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="RuoVea.ExIdGen" Version="10.0.0.1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="RuoVea.ExIdGen" Version="10.0.0.1" />
<PackageReference Include="RuoVea.ExIdGen" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add RuoVea.ExIdGen --version 10.0.0.1
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: RuoVea.ExIdGen, 10.0.0.1"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package RuoVea.ExIdGen@10.0.0.1
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=RuoVea.ExIdGen&version=10.0.0.1
#tool nuget:?package=RuoVea.ExIdGen&version=10.0.0.1
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
📋 RuoVea.ExIdGen 组件概览
RuoVea.ExIdGen 是一个高性能的分布式唯一ID生成器,基于雪花漂移算法,支持数据中心ID和秒级时间戳,适用于分布式系统环境。
🏗️ 核心算法架构
1. 雪花漂移算法原理
雪花算法ID结构(64位):
| 1位符号位 | 41位时间戳 | 数据中心ID | 机器ID | 序列号 |
|----------|------------|------------|---------|--------|
2. 配置系统
配置文件
{
"IdGenerator": {
/* 机器ID,用于唯一Id的生成 (0-1023) */
"WorkerId": 2,
/* 默认值6,取值范围 [3, 21],序列数位长+机器码位长不超过22 */
"SeqBitLength": 6
}
}
配置说明
- WorkerId: 机器标识,范围 0-1023,确保分布式环境中每个实例唯一
- SeqBitLength: 序列号位长,控制同一毫秒内可生成的ID数量
🔧 核心功能类
1. IdGenerator 静态类
主要功能方法
生成数值型ID
// 生成雪花算法数值型ID (long)
long id = IdGenerator.Id;
// 使用示例
long orderId = IdGenerator.Id;
long userId = IdGenerator.Id;
生成字符串ID
// 生成带前缀的字符串ID
string id = IdGenerator.IdStr("demo");
// 使用示例
string orderNo = IdGenerator.IdStr("ORD"); // 结果: "ORD1234567890123456"
string userId = IdGenerator.IdStr("USR"); // 结果: "USR1234567890123456"
生成自动编号
// 生成时间序列编号 格式: yyyyMMddHHmmssfff + 随机数
string no = IdGenerator.No();
// 使用示例
string orderNumber = IdGenerator.No(); // 结果: "20240101123045987654"
🚀 完整使用示例
1. 基础ID生成
public class IdGenerationService
{
// 生成订单ID
public long GenerateOrderId()
{
return IdGenerator.Id;
}
// 生成带业务前缀的订单编号
public string GenerateOrderNumber()
{
return IdGenerator.IdStr("ORD");
}
// 生成用户ID
public long GenerateUserId()
{
return IdGenerator.Id;
}
// 生成带业务前缀的用户编号
public string GenerateUserNumber()
{
return IdGenerator.IdStr("USR");
}
}
2. 实体类ID生成
public abstract class BaseEntity
{
public long Id { get; set; }
public string Code { get; set; }
protected BaseEntity()
{
// 实体创建时自动生成ID
Id = IdGenerator.Id;
Code = IdGenerator.IdStr(GetEntityPrefix());
}
protected abstract string GetEntityPrefix();
}
public class Order : BaseEntity
{
public string OrderName { get; set; }
public decimal Amount { get; set; }
public Order()
{
// 生成订单特定编号
OrderNumber = IdGenerator.No();
}
public string OrderNumber { get; set; }
protected override string GetEntityPrefix()
{
return "ORD";
}
}
public class User : BaseEntity
{
public string UserName { get; set; }
public string Email { get; set; }
protected override string GetEntityPrefix()
{
return "USR";
}
}
3. 分布式系统ID生成
public class DistributedIdService
{
private readonly string _servicePrefix;
public DistributedIdService(string serviceName)
{
_servicePrefix = serviceName.ToUpper();
}
// 生成分布式事务ID
public string GenerateTransactionId()
{
return IdGenerator.IdStr($"TXN_{_servicePrefix}");
}
// 生成消息ID
public string GenerateMessageId()
{
return IdGenerator.IdStr($"MSG_{_servicePrefix}");
}
// 生成批次ID
public string GenerateBatchId()
{
return IdGenerator.IdStr($"BCH_{_servicePrefix}");
}
// 生成跟踪ID
public string GenerateTraceId()
{
var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
var random = new Random().Next(1000, 9999);
return $"{_servicePrefix}_{timestamp}_{random}";
}
}
4. 批量ID生成
public class BatchIdGenerator
{
// 批量生成ID
public List<long> GenerateBatchIds(int count)
{
var ids = new List<long>();
for (int i = 0; i < count; i++)
{
ids.Add(IdGenerator.Id);
}
return ids;
}
// 批量生成带前缀的ID
public List<string> GenerateBatchStringIds(string prefix, int count)
{
var ids = new List<string>();
for (int i = 0; i < count; i++)
{
ids.Add(IdGenerator.IdStr(prefix));
}
return ids;
}
// 生成唯一编号列表
public List<string> GenerateBatchNumbers(int count)
{
var numbers = new List<string>();
for (int i = 0; i < count; i++)
{
numbers.Add(IdGenerator.No());
}
return numbers;
}
}
5. ID生成策略管理
public class IdGenerationStrategy
{
private readonly Dictionary<string, Func<string>> _strategies;
public IdGenerationStrategy()
{
_strategies = new Dictionary<string, Func<string>>
{
["order"] = () => IdGenerator.IdStr("ORD"),
["user"] = () => IdGenerator.IdStr("USR"),
["product"] = () => IdGenerator.IdStr("PRD"),
["category"] = () => IdGenerator.IdStr("CAT"),
["payment"] = () => IdGenerator.IdStr("PAY"),
["refund"] = () => IdGenerator.IdStr("REF"),
["shipment"] = () => IdGenerator.IdStr("SHP"),
["invoice"] = () => IdGenerator.IdStr("INV")
};
}
// 根据业务类型生成ID
public string GenerateId(string businessType)
{
if (_strategies.TryGetValue(businessType.ToLower(), out var generator))
{
return generator();
}
// 默认生成方式
return IdGenerator.IdStr(businessType.ToUpper());
}
// 注册自定义生成策略
public void RegisterStrategy(string businessType, string prefix)
{
_strategies[businessType.ToLower()] = () => IdGenerator.IdStr(prefix);
}
}
6. 高性能ID生成服务
public class HighPerformanceIdService
{
private readonly object _lockObject = new object();
private long _lastTimestamp = -1L;
private long _sequence = 0L;
// 自定义高性能ID生成(基于原始雪花算法)
public long GenerateHighPerfId()
{
lock (_lockObject)
{
var timestamp = TimeGen();
if (timestamp < _lastTimestamp)
{
throw new Exception("时钟回拨异常");
}
if (_lastTimestamp == timestamp)
{
_sequence = (_sequence + 1) & GetMaxSequence();
if (_sequence == 0)
{
timestamp = TilNextMillis(_lastTimestamp);
}
}
else
{
_sequence = 0L;
}
_lastTimestamp = timestamp;
return ((timestamp - GetTwepoch()) << GetTimestampLeftShift())
| (GetWorkerId() << GetSequenceBits())
| _sequence;
}
}
private long TimeGen()
{
return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
}
private long TilNextMillis(long lastTimestamp)
{
var timestamp = TimeGen();
while (timestamp <= lastTimestamp)
{
timestamp = TimeGen();
}
return timestamp;
}
// 以下为配置相关方法,需要根据实际配置实现
private long GetTwepoch() => 1288834974657L; // Twitter雪花算法起始时间戳
private long GetWorkerId() => 1L; // 从配置获取
private long GetSequenceBits() => 12L; // 序列号位数
private long GetMaxSequence() => ~(-1L << (int)GetSequenceBits());
private long GetTimestampLeftShift() => GetSequenceBits() + GetWorkerIdBits();
private long GetWorkerIdBits() => 10L; // 工作ID位数
}
7. ID解析工具
public class IdParser
{
// 解析雪花算法ID的各个组成部分
public static (DateTime timestamp, long workerId, long sequence) ParseSnowflakeId(long id)
{
// 雪花算法结构:时间戳 | 工作节点ID | 序列号
var timestamp = (id >> 22) + 1288834974657L; // 加上起始时间戳
var workerId = (id >> 12) & 0x3FF; // 10位工作节点ID
var sequence = id & 0xFFF; // 12位序列号
var dateTime = DateTimeOffset.FromUnixTimeMilliseconds(timestamp).DateTime;
return (dateTime, workerId, sequence);
}
// 验证ID是否有效
public static bool IsValidSnowflakeId(long id)
{
try
{
var (timestamp, workerId, sequence) = ParseSnowflakeId(id);
// 检查时间戳是否在合理范围内
if (timestamp < new DateTime(2020, 1, 1) || timestamp > DateTime.Now.AddYears(1))
return false;
// 检查工作节点ID是否在有效范围内
if (workerId < 0 || workerId > 1023)
return false;
// 检查序列号是否在有效范围内
if (sequence < 0 || sequence > 4095)
return false;
return true;
}
catch
{
return false;
}
}
// 获取ID的创建时间
public static DateTime GetIdCreationTime(long id)
{
var (timestamp, _, _) = ParseSnowflakeId(id);
return timestamp;
}
}
8. 配置管理
public class IdGeneratorConfig
{
public long WorkerId { get; set; } = 1;
public int SeqBitLength { get; set; } = 6;
// 从配置文件加载配置
public static IdGeneratorConfig LoadFromConfig(IConfiguration configuration)
{
return configuration.GetSection("IdGenerator").Get<IdGeneratorConfig>()
?? new IdGeneratorConfig();
}
// 从环境变量加载配置
public static IdGeneratorConfig LoadFromEnvironment()
{
return new IdGeneratorConfig
{
WorkerId = long.Parse(Environment.GetEnvironmentVariable("IDGENERATOR_WORKER_ID") ?? "1"),
SeqBitLength = int.Parse(Environment.GetEnvironmentVariable("IDGENERATOR_SEQ_BIT_LENGTH") ?? "6")
};
}
// 验证配置有效性
public bool Validate()
{
if (WorkerId < 0 || WorkerId > 1023)
{
throw new ArgumentException("WorkerId must be between 0 and 1023");
}
if (SeqBitLength < 3 || SeqBitLength > 21)
{
throw new ArgumentException("SeqBitLength must be between 3 and 21");
}
return true;
}
}
9. 集成使用示例
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// 配置ID生成器
ConfigureIdGenerator(builder.Configuration);
var app = builder.Build();
// 使用ID生成器
app.MapGet("/api/orders/new", () =>
{
var orderId = IdGenerator.Id;
var orderNumber = IdGenerator.IdStr("ORD");
var autoNumber = IdGenerator.No();
return new
{
OrderId = orderId,
OrderNumber = orderNumber,
AutoNumber = autoNumber,
GeneratedAt = DateTime.Now
};
});
app.Run();
}
private static void ConfigureIdGenerator(IConfiguration configuration)
{
// 可以从配置文件、环境变量或服务发现中获取WorkerId
var workerId = GetWorkerIdFromEnvironment();
// 在实际生产环境中,需要确保每个实例的WorkerId唯一
// 可以通过数据库、配置中心、或服务注册中心来分配
}
private static long GetWorkerIdFromEnvironment()
{
// 从环境变量获取,如果没有则生成随机值
var envWorkerId = Environment.GetEnvironmentVariable("WORKER_ID");
if (!string.IsNullOrEmpty(envWorkerId) && long.TryParse(envWorkerId, out long workerId))
{
return workerId;
}
// 生成基于机器特征的WorkerId
return GenerateMachineSpecificWorkerId();
}
private static long GenerateMachineSpecificWorkerId()
{
// 基于机器名生成WorkerId
var machineName = Environment.MachineName;
var hash = machineName.GetHashCode();
return Math.Abs(hash) % 1024; // 确保在0-1023范围内
}
}
🎯 性能特点
1. 高并发性能
- 单机每秒可生成数十万ID
- 无锁设计,线程安全
- 支持高并发场景
2. 分布式友好
- 支持多数据中心部署
- 每个实例可配置唯一WorkerId
- 避免ID冲突
3. 时间有序
- ID按时间递增
- 便于数据库索引优化
- 支持按时间范围查询
4. 可解析性
- ID包含时间信息
- 可追溯生成时间
- 便于调试和监控
🔧 最佳实践
- WorkerId管理:在分布式环境中确保每个实例的WorkerId唯一
- 时钟同步:确保所有机器时钟同步,避免时钟回拨
- 监控告警:监控ID生成异常,如时钟回拨情况
- 容量规划:根据业务量合理设置序列号位数
这个ID生成器组件为分布式系统提供了高性能、可扩展的唯一ID生成解决方案,适用于各种需要唯一标识的业务场景。
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net10.0
- Microsoft.Extensions.Configuration.Binder (>= 9.0.7)
NuGet packages (3)
Showing the top 3 NuGet packages that depend on RuoVea.ExIdGen:
| Package | Downloads |
|---|---|
|
RuoVea.ExSugar
Sqlsugar扩展 快速注入,支持简体中文、繁体中文、粤语、日语、法语、英语.使用方式:service.AddSqlsugar();继承RestFulLog 重写异常日志,操作日志,差异日志 |
|
|
RuoVea.ExWeb
CorsUrls、IPLimit、SafeIps、Jwt 配置 |
|
|
RuoVea.QuartzNetUI
QuartzNet UI界面 执行脚本地址:https://gitee.com/starry123/ruovea-quartznet-ui/tree/develop/Doc/Sql |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 10.0.0.1 | 531 | 11/21/2025 |
| 9.0.0.1 | 620 | 11/21/2025 |
| 9.0.0 | 563 | 7/25/2025 |
| 8.0.1.1 | 2,518 | 11/21/2025 |
| 8.0.1 | 6,297 | 8/26/2024 |
| 8.0.0 | 530 | 11/24/2023 |
| 7.0.1.1 | 2,854 | 11/21/2025 |
| 7.0.1 | 7,542 | 8/26/2024 |
| 7.0.0 | 269 | 7/23/2024 |
| 6.0.1.2 | 3,456 | 11/21/2025 |
| 6.0.1 | 15,758 | 8/26/2024 |
| 6.0.0 | 2,826 | 2/9/2022 |
| 5.0.3.1 | 579 | 11/21/2025 |
| 5.0.3 | 658 | 8/26/2024 |
| 5.0.2 | 3,845 | 11/25/2021 |
| 2.1.1.2 | 389 | 11/21/2025 |
| 2.1.1.1 | 218 | 11/24/2023 |
| 2.1.1 | 598 | 6/9/2022 |
| 2.0.0.1 | 390 | 11/21/2025 |
| 2.0.0 | 200 | 9/22/2024 |
Loading failed