using HashidsNet;
using Yitter.IdGenerator;
namespace Easy.Core;
public static class YitIdHelperExtension
{
///
/// 盐值
///
private const string Salt = "dkjsDLVK1S7y5be8XYzoq0C2nHaEmBfA";
///
/// 注册雪花ID服务(默认配置)
///
///
public static void AddIdGenerator(this IServiceCollection service)
{
service.AddIdGenerator(new IdGeneratorOptions(0));
}
///
/// 注册雪花ID服务(自定义配置)
///
///
///
public static void AddIdGenerator(this IServiceCollection service, string sectionName)
{
var options = App.GetConfig(sectionName) ?? new IdGeneratorOptions(0);
options.BaseTime = options.BaseTime.ToUniversalTime();
YitIdHelper.SetIdGenerator(options);
service.AddSingleton(new DefaultIdGenerator(options));
}
///
/// 注册雪花ID服务(自定义配置)
///
///
/// 配置
public static void AddIdGenerator(this IServiceCollection service, IdGeneratorOptions options)
{
options.BaseTime = options.BaseTime.ToUniversalTime();
YitIdHelper.SetIdGenerator(options);
service.AddSingleton(new DefaultIdGenerator(options));
}
///
/// 生成ID
///
///
///
public static long NextId(this IIdGenerator generator)
{
return generator.NewLong();
}
///
/// 加密ID(生成短ID)
///
///
/// long类型ID
/// 盐值
///
public static string Encode(this IIdGenerator generator, long id, string salt = Salt)
{
return new Hashids(salt).EncodeLong(id);
}
///
/// 解密加密ID(解密短ID)
///
///
/// 密文
/// 盐值
///
public static long Decode(this IIdGenerator generator, string text, string salt = Salt)
{
return new Hashids(salt).DecodeSingleLong(text);
}
}