学海无涯

导航

雪花漂移ID,Yitter.IdGenerator 封装成一个适用于 ASP.NET Core 6.0 的服务组件

封装目标

  • Program.cs 中注册服务

  • 提供一个 IIdGenerator 接口

  • 实现类使用 Yitter.IdGenerator 生成唯一 ID

  • 支持依赖注入,方便在 Controller、Service 中调用

安装程序包:

dotnet add package Yitter.IdGenerator

定义接口:

public interface IIdGenerator
{
    long NewId();
}

实现接口:

using Yitter.IdGenerator;

public class YitterIdGenerator : IIdGenerator
{
    public YitterIdGenerator()
    {
        var options = new IdGeneratorOptions(workerId: 1); // WorkerId 可根据部署环境动态设置
        YitIdHelper.SetIdGenerator(options);
    }

    public long NewId()
    {
        return YitIdHelper.NextId();
    }
}

Program.cs 中注册服务

builder.Services.AddSingleton<IIdGenerator, YitterIdGenerator>();

在 Controller 或 Service 中使用

public class OrderService
{
    private readonly IIdGenerator _idGenerator;

    public OrderService(IIdGenerator idGenerator)
    {
        _idGenerator = idGenerator;
    }

    public void CreateOrder()
    {
        long orderId = _idGenerator.NewId();
        Console.WriteLine($"新订单 ID: {orderId}");
    }
}

 

可选扩展:WorkerId 自动分配

如果你部署在 Kubernetes 或容器环境,可以考虑通过环境变量或 Redis 分布式锁自动分配 WorkerId,避免冲突。

引用:

https://github.com/yitter/IdGenerator/blob/master/C%23/source/Yitter.IdGenerator/YitIdHelper.cs

https://github.com/yitter/idgenerator

 

 

  

  

  

 

 

 

posted on 2025-12-03 09:59  宁静致远.  阅读(1)  评论(0)    收藏  举报