forked from anjoy8/Blog.Core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIdGeneratorUtility.cs
More file actions
69 lines (60 loc) · 2.43 KB
/
IdGeneratorUtility.cs
File metadata and controls
69 lines (60 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using Blog.Core.Common.DB;
using Blog.Core.Common.Option;
using Microsoft.Extensions.Hosting;
using Serilog;
using SnowflakeId.AutoRegister.Builder;
using SnowflakeId.AutoRegister.Interfaces;
using SqlSugar;
using Yitter.IdGenerator;
namespace Blog.Core.Common.Utility;
public class IdGeneratorUtility
{
private static readonly Lazy<IAutoRegister> AutoRegister = new(() =>
{
var builder = new AutoRegisterBuilder()
// Register Option
// Use the following line to set the identifier.
// Recommended setting to distinguish multiple applications on a single machine
.SetExtraIdentifier(App.Configuration["urls"] ?? string.Empty)
// Use the following line to set the WorkerId scope.
.SetWorkerIdScope(1, 30)
// Use the following line to set the register option.
// .SetRegisterOption(option => {})
;
var redisOptions = App.GetOptions<RedisOptions>();
if (redisOptions.Enable)
// Use the following line to use the Redis store.
builder.UseRedisStore(redisOptions.ConnectionString);
else if (BaseDBConfig.LogConfig != null && BaseDBConfig.LogConfig.DbType == DbType.SqlServer)
// Use the following line to use the SQL Server store.
builder.UseSqlServerStore(BaseDBConfig.LogConfig.ConnectionString);
else
// Use the following line to use the default store.
// Only suitable for standalone use, local testing, etc.
builder.UseDefaultStore();
App.GetService<IHostApplicationLifetime>(false).ApplicationStopping.Register(UnRegister);
return builder.Build();
});
private static readonly Lazy<IIdGenerator> _idGenInstance = new(() =>
{
var config = AutoRegister.Value.Register();
//WorkerId DataCenterId 取值 1-31
var options = new IdGeneratorOptions
{
WorkerId = (ushort)config.WorkerId,
};
IIdGenerator idGenInstance = new DefaultIdGenerator(options);
return idGenInstance;
});
private static IIdGenerator IdGenInstance => _idGenInstance.Value;
public static long NextId()
{
return IdGenInstance.NewLong();
}
public static void UnRegister()
{
if (!AutoRegister.IsValueCreated) return;
AutoRegister.Value.UnRegister();
Log.Information("Snowflake Id Unregistered");
}
}