Skip to content

Commit

Permalink
✨⚡️雪花Id优化
Browse files Browse the repository at this point in the history
1.统一使用 Yitter.IdGenerator 生成雪花Id、
2.使用 SnowflakeId.AutoRegister 自动注册WorkerId

静态使用:IdGeneratorUtility.NextId()
  • Loading branch information
LemonNoCry committed Jul 3, 2024
1 parent 0d5fb83 commit 2d73502
Show file tree
Hide file tree
Showing 10 changed files with 119 additions and 17 deletions.
6 changes: 6 additions & 0 deletions Blog.Core.Api/Blog.Core.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions Blog.Core.Api/Controllers/ValuesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
using System.Text;
using Blog.Core.Common.Utlilty;

namespace Blog.Core.Controllers
{
Expand Down Expand Up @@ -472,6 +473,17 @@ public string TestOption()
{
return _seqOptions.ToJson();
}

/// <summary>
/// 获取雪花Id
/// </summary>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public long GetSnowflakeId()
{
return IdGeneratorUtility.NextId();
}
}

public class ClaimDto
Expand Down
6 changes: 5 additions & 1 deletion Blog.Core.Common/Blog.Core.Common.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,16 @@
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.Elasticsearch" Version="9.0.3" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="StackExchange.Redis" Version="2.7.4" />
<PackageReference Include="SnowflakeId.AutoRegister" Version="1.0.1" />
<PackageReference Include="SnowflakeId.AutoRegister.SqlServer" Version="1.0.0" />
<PackageReference Include="SnowflakeId.AutoRegister.StackExchangeRedis" Version="1.0.0" />
<PackageReference Include="StackExchange.Redis" Version="2.8.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.2.0" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.1-dev-00771" />

<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Yitter.IdGenerator" Version="1.0.14" />

</ItemGroup>

Expand Down
14 changes: 9 additions & 5 deletions Blog.Core.Common/DB/Aop/SqlsugarAop.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@
using System;
using Serilog;
using Blog.Core.Common.LogHelper;
using Blog.Core.Common.Utlilty;
using Blog.Core.Model;

namespace Blog.Core.Common.DB.Aop;

public static class SqlSugarAop
{
public static void OnLogExecuting(ISqlSugarClient sqlSugarScopeProvider, string user, string table, string operate, string sql, SugarParameter[] p, ConnectionConfig config)
public static void OnLogExecuting(ISqlSugarClient sqlSugarScopeProvider, string user, string table, string operate, string sql,
SugarParameter[] p, ConnectionConfig config)
{
try
{
Expand All @@ -25,7 +27,8 @@ public static void OnLogExecuting(ISqlSugarClient sqlSugarScopeProvider, string
{
using (LogContextExtension.Create.SqlAopPushProperty(sqlSugarScopeProvider))
{
Log.Information("------------------ \r\n User:[{User}] Table:[{Table}] Operate:[{Operate}] ConnId:[{ConnId}]【SQL语句】: \r\n {Sql}",
Log.Information(
"------------------ \r\n User:[{User}] Table:[{Table}] Operate:[{Operate}] ConnId:[{ConnId}]【SQL语句】: \r\n {Sql}",
user, table, operate, config.ConfigId, UtilMethods.GetNativeSql(sql, p));
}
}
Expand All @@ -42,7 +45,7 @@ public static void DataExecuting(object oldValue, DataFilterModel entityInfo)
{
if (rootEntity.Id == 0)
{
rootEntity.Id = SnowFlakeSingle.Instance.NextId();
rootEntity.Id = IdGeneratorUtility.NextId();
}
}

Expand Down Expand Up @@ -113,7 +116,8 @@ public static void DataExecuting(object oldValue, DataFilterModel entityInfo)
if (App.User?.ID > 0 && dyCreateId != null && dyCreateId.GetValue(entityInfo.EntityValue) == null)
dyCreateId.SetValue(entityInfo.EntityValue, App.User.ID);

if (dyCreateTime != null && dyCreateTime.GetValue(entityInfo.EntityValue) != null && (DateTime)dyCreateTime.GetValue(entityInfo.EntityValue) == DateTime.MinValue)
if (dyCreateTime != null && dyCreateTime.GetValue(entityInfo.EntityValue) != null &&
(DateTime)dyCreateTime.GetValue(entityInfo.EntityValue) == DateTime.MinValue)
dyCreateTime.SetValue(entityInfo.EntityValue, DateTime.Now);

break;
Expand Down Expand Up @@ -155,4 +159,4 @@ private static string GetParas(SugarParameter[] pars)

return key;
}
}
}
9 changes: 5 additions & 4 deletions Blog.Core.Common/Seed/SeedData/SubBusinessDataSeedData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using SqlSugar;
using System.Collections.Generic;
using System.Threading.Tasks;
using Blog.Core.Common.Utlilty;

namespace Blog.Core.Common.Seed.SeedData;

Expand Down Expand Up @@ -29,13 +30,13 @@ await db.Insertable<SubLibraryBusinessTable>(new List<SubLibraryBusinessTable>()
{
new()
{
Id = SnowFlakeSingle.Instance.NextId(),
Id = IdGeneratorUtility.NextId(),
Name = "王五业务数据1",
Amount = 100,
},
new()
{
Id = SnowFlakeSingle.Instance.NextId(),
Id = IdGeneratorUtility.NextId(),
Name = "王五业务数据2",
Amount = 1000,
},
Expand All @@ -50,13 +51,13 @@ await db.Insertable<SubLibraryBusinessTable>(new List<SubLibraryBusinessTable>()
{
new()
{
Id = SnowFlakeSingle.Instance.NextId(),
Id = IdGeneratorUtility.NextId(),
Name = "赵六业务数据1",
Amount = 50,
},
new()
{
Id = SnowFlakeSingle.Instance.NextId(),
Id = IdGeneratorUtility.NextId(),
Name = "赵六业务数据2",
Amount = 60,
},
Expand Down
69 changes: 69 additions & 0 deletions Blog.Core.Common/Utlilty/IdGeneratorUtility.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,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.Utlilty;

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");
}
}
3 changes: 3 additions & 0 deletions Blog.Core.Extensions/ServiceExtensions/SqlsugarSetup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using SqlSugar;
using Blog.Core.Common.Caches;
using System.Text.RegularExpressions;
using Blog.Core.Common.Utlilty;

namespace Blog.Core.Extensions
{
Expand All @@ -21,6 +22,8 @@ public static void AddSqlsugarSetup(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));

StaticConfig.CustomSnowFlakeFunc = IdGeneratorUtility.NextId;

// 默认添加主数据库连接
if (!AppSettings.app("MainDB").IsNullOrEmpty())
{
Expand Down
5 changes: 3 additions & 2 deletions Blog.Core.Services/GuestbookServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System;
using System.Threading.Tasks;
using Blog.Core.Common.DB;
using Blog.Core.Common.Utlilty;
using Blog.Core.Repository.UnitOfWorks;
using SqlSugar;

Expand Down Expand Up @@ -227,7 +228,7 @@ await Db.Insertable(new Guestbook()

await Db.Insertable(new PasswordLib()
{
PLID = SnowFlakeSingle.Instance.NextId(),
PLID = IdGeneratorUtility.NextId(),
IsDeleted = false,
plAccountName = "aaa",
plCreateTime = DateTime.Now
Expand Down Expand Up @@ -257,7 +258,7 @@ await db.Insertable(new Guestbook()

await db.Insertable(new PasswordLib()
{
PLID = SnowFlakeSingle.Instance.NextId(),
PLID = IdGeneratorUtility.NextId(),
IsDeleted = false,
plAccountName = "aaa",
plCreateTime = DateTime.Now
Expand Down
7 changes: 4 additions & 3 deletions Blog.Core.Services/PasswordLibServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Threading.Tasks;
using Blog.Core.Common;
using Blog.Core.Common.DB;
using Blog.Core.Common.Utlilty;
using Blog.Core.IRepository.Base;
using Blog.Core.IServices;
using Blog.Core.Model.Models;
Expand Down Expand Up @@ -31,7 +32,7 @@ public async Task<bool> TestTranPropagation2()
{
await _dal.Add(new PasswordLib()
{
PLID = SnowFlakeSingle.Instance.NextId(),
PLID = IdGeneratorUtility.NextId(),
IsDeleted = false,
plAccountName = "aaa",
plCreateTime = DateTime.Now
Expand All @@ -58,7 +59,7 @@ public async Task<bool> TestTranPropagationTran2()
{
await db.Insertable(new PasswordLib()
{
PLID = SnowFlakeSingle.Instance.NextId(),
PLID = IdGeneratorUtility.NextId(),
IsDeleted = false,
plAccountName = "aaa",
plCreateTime = DateTime.Now
Expand All @@ -76,7 +77,7 @@ public async Task<bool> TestTranPropagationTran3()
Console.WriteLine("");
await db.Insertable(new PasswordLib()
{
PLID = SnowFlakeSingle.Instance.NextId(),
PLID = IdGeneratorUtility.NextId(),
IsDeleted = false,
plAccountName = "aaa",
plCreateTime = DateTime.Now
Expand Down
5 changes: 3 additions & 2 deletions Blog.Core.Tasks/QuartzNet/Jobs/Job_Blogs_Quartz.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Quartz;
using System;
using System.Threading.Tasks;
using Blog.Core.Common.Utlilty;
using Blog.Core.Model.Models;
using Blog.Core.Repository.UnitOfWorks;
using SqlSugar;
Expand Down Expand Up @@ -49,7 +50,7 @@ await db.Insertable(new Guestbook()
}).ExecuteReturnSnowflakeIdAsync();
await db.Insertable(new PasswordLib()
{
PLID = SnowFlakeSingle.Instance.NextId(),
PLID = IdGeneratorUtility.NextId(),
IsDeleted = false,
plAccountName = "aaa",
plCreateTime = DateTime.Now
Expand All @@ -59,7 +60,7 @@ await db.Insertable(new PasswordLib()
Console.WriteLine(db.ContextID);
await db.Insertable(new PasswordLib()
{
PLID = SnowFlakeSingle.Instance.NextId(),
PLID = IdGeneratorUtility.NextId(),
IsDeleted = false,
plAccountName = "aaa",
plCreateTime = DateTime.Now
Expand Down

0 comments on commit 2d73502

Please sign in to comment.