├── .gitignore ├── ClockSnowFlake.sln ├── LICENSE ├── README.md ├── build └── nuget.props ├── media ├── algorithm.png └── nuget-icon.png ├── sample └── ClockSnowFlake.Demo.WebApi │ ├── ClockSnowFlake.Demo.WebApi.csproj │ ├── Controllers │ └── SnowFlakeController.cs │ ├── Program.cs │ └── appsettings.json ├── src └── ClockSnowFlake │ ├── ClockSnowFlake.csproj │ ├── Extensions │ └── ServiceCollectionExtensions.cs │ ├── Generator │ ├── ClockSnowFlakeIdGenerator.cs │ ├── IIdGenerator.cs │ └── ILongGenerator.cs │ ├── Helpers │ └── SnowflakeHelper.cs │ ├── IdGener.cs │ ├── Ids │ └── ClockSnowflakeId.cs │ └── Options │ ├── SnowFakeOptionsConst.cs │ └── SnowFlakeOptions.cs └── test └── ClockSnowFlake.Unitests ├── ClockSnowFlake.Unitests.csproj └── ClockSnowFlakeTest.cs /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | # tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | /src/AIAgain.Apollo.GatewayServer.Host/App_Data/logs 290 | /src/AIAgain.Apollo.GatewayServer.Host/App_Data/logs 291 | /doc/protoc-3.6.1 292 | /trunk 293 | /src/AIAgain.RMServer.MessageConsumer.Host/appsettings.local.json 294 | /src/AIAgain.Apollo.MessageService.Host/appsettings.local.json 295 | /src/AIAgain.EnterpriseWeChat.TaskAPI.RepositoriesTests/Client/ClientExtendRepositoryTests.cs 296 | /src/AIAgain.EnterpriseWeChat.TaskAPI.RepositoriesTests/Client 297 | /src/AIAgain.EnterpriseWeChat.TaskAPI.RepositoriesTests 298 | /build/nupkg 299 | -------------------------------------------------------------------------------- /ClockSnowFlake.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.2.32526.322 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sample", "sample", "{D3AC3759-BB2B-4240-A451-6C9F5BF4BD55}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A22F5536-64A9-4686-937C-A3E16073B615}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{54301E01-139F-4FBF-B993-1E128D903500}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClockSnowFlake.Unitests", "test\ClockSnowFlake.Unitests\ClockSnowFlake.Unitests.csproj", "{D1CBF717-BF37-4D9B-833D-65385C87BCDE}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "build", "build", "{1693E868-A55C-45FD-88D5-55A5E225F82D}" 15 | ProjectSection(SolutionItems) = preProject 16 | build\nuget.props = build\nuget.props 17 | EndProjectSection 18 | EndProject 19 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClockSnowFlake", "src\ClockSnowFlake\ClockSnowFlake.csproj", "{219C09A2-3D87-4A87-999C-1276389B6628}" 20 | EndProject 21 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClockSnowFlake.Demo.WebApi", "sample\ClockSnowFlake.Demo.WebApi\ClockSnowFlake.Demo.WebApi.csproj", "{72D4E1B8-B2FF-4A30-B713-F1E9E7B7ACC3}" 22 | EndProject 23 | Global 24 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 25 | Debug|Any CPU = Debug|Any CPU 26 | Release|Any CPU = Release|Any CPU 27 | EndGlobalSection 28 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 29 | {D1CBF717-BF37-4D9B-833D-65385C87BCDE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 30 | {D1CBF717-BF37-4D9B-833D-65385C87BCDE}.Debug|Any CPU.Build.0 = Debug|Any CPU 31 | {D1CBF717-BF37-4D9B-833D-65385C87BCDE}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 | {D1CBF717-BF37-4D9B-833D-65385C87BCDE}.Release|Any CPU.Build.0 = Release|Any CPU 33 | {219C09A2-3D87-4A87-999C-1276389B6628}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {219C09A2-3D87-4A87-999C-1276389B6628}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {219C09A2-3D87-4A87-999C-1276389B6628}.Release|Any CPU.ActiveCfg = Release|Any CPU 36 | {219C09A2-3D87-4A87-999C-1276389B6628}.Release|Any CPU.Build.0 = Release|Any CPU 37 | {72D4E1B8-B2FF-4A30-B713-F1E9E7B7ACC3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {72D4E1B8-B2FF-4A30-B713-F1E9E7B7ACC3}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {72D4E1B8-B2FF-4A30-B713-F1E9E7B7ACC3}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {72D4E1B8-B2FF-4A30-B713-F1E9E7B7ACC3}.Release|Any CPU.Build.0 = Release|Any CPU 41 | EndGlobalSection 42 | GlobalSection(SolutionProperties) = preSolution 43 | HideSolutionNode = FALSE 44 | EndGlobalSection 45 | GlobalSection(NestedProjects) = preSolution 46 | {D1CBF717-BF37-4D9B-833D-65385C87BCDE} = {54301E01-139F-4FBF-B993-1E128D903500} 47 | {219C09A2-3D87-4A87-999C-1276389B6628} = {A22F5536-64A9-4686-937C-A3E16073B615} 48 | {72D4E1B8-B2FF-4A30-B713-F1E9E7B7ACC3} = {D3AC3759-BB2B-4240-A451-6C9F5BF4BD55} 49 | EndGlobalSection 50 | GlobalSection(ExtensibilityGlobals) = postSolution 51 | SolutionGuid = {D1D2AABE-A492-4DDE-AE64-AF0ACB4F97DE} 52 | EndGlobalSection 53 | EndGlobal 54 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Bryan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ClockSnowFlake 2 | 3 | ## Nuget包 4 | 5 | | Package Name | Version | Downloads 6 | |--------------| ------- | ---- 7 | | ClockSnowFlake | [![NuGet](https://img.shields.io/nuget/v/ClockSnowFlake)](https://www.nuget.org/packages/ClockSnowFlake) | [![NuGet](https://img.shields.io/nuget/dt/ClockSnowFlake)](https://www.nuget.org/packages/ClockSnowFlake)| 8 | 9 | --------- 10 | 11 | # `ClockSnowFlake` 12 | > 这是一个基于.NET开源的改进版雪花算法组件,解决了原生雪花算法的时间回拨问题 13 | 14 | ------- 15 | 16 | ## 功能介绍 17 | - [x] 支持自定义WorkId 18 | - [x] 基于时间序列,解决时间回拨问题 19 | - [x] 傻瓜式配置,开箱即用 20 | - [x] [关键实现代码](https://github.com/Bryan-Cyf/ClockSnowFlake/blob/master/src/ClockSnowFlake/Ids/ClockSnowflakeId.cs) 21 | 22 | ## 文档资料 23 | - [x] [『ClockSnowFlake』.Net项目接入文档](https://chenyuefeng.blog.csdn.net/article/details/129998719) 24 | - [x] [『SnowFlake』雪花算法的详解及时间回拨解决方案](https://chenyuefeng.blog.csdn.net/article/details/128245550) 25 | 26 | --------- 27 | 28 | 29 | # 项目接入 30 | 31 | ## Step 1 : 安装包,通过Nuget安装包 32 | 33 | ```powershell 34 | Install-Package ClockSnowFlake 35 | ``` 36 | 37 | ## Step 2 : 配置 Startup 启动类 38 | 39 | ```csharp 40 | public class Startup 41 | { 42 | //... 43 | 44 | public void ConfigureServices(IServiceCollection services) 45 | { 46 | //configuration 47 | services.AddSnowFlakeId(x => x.WorkId = 2); 48 | } 49 | } 50 | ``` 51 | 52 | ## Step 3 : Id生成器使用 53 | 54 | ```csharp 55 | [ApiController] 56 | [Route("[controller]/[action]")] 57 | public class SnowFlakeController : ControllerBase 58 | { 59 | /// 60 | /// 获取Id 61 | /// 62 | [HttpGet] 63 | public long GetId() 64 | { 65 | return IdGener.GetLong(); 66 | } 67 | } 68 | ``` 69 | 70 | # 雪花算法的时间回拨问题 71 | 72 | ## 问题描述 73 | 74 | 简单说就是时间被调整回到了之前的时间,由于雪花算法重度依赖机器的当前时间,所以一旦发生时间回拨,将有可能导致生成的 ID 可能与此前已经生成的某个 ID 重复(前提是刚好在同一毫秒生成 ID 时序列号也刚好一致),这就是雪花算法最经常讨论的问题——时间回拨 75 | 76 | ## 现象引发 77 | 78 | - 网络时间校准 79 | - 人工设置 80 | - 出现负闰秒 81 | 82 | ## 原生雪花算法的处理方式 83 | 84 | - 直接抛出异常 85 | 86 | 在雪花算法原本的实现中,针对这种问题,算法本身只是返回错误,由应用另行决定处理逻辑,如果是在一个并发不高或者请求量不大的业务系统中,错误等待或者重试的策略问题不大,但是如果是在一个高并发的系统中,这种策略显得过于粗暴 87 | 88 | --------- 89 | 90 | # 基于时钟序列解决时间回拨的方案 91 | 92 | ## 简介 93 | 94 | > 这里采用的是一种基于修改扩展位的思路,基于时钟序列的雪花算法 95 | > 二进制64位长整型数字:1bit保留 + 41bit时间戳 + 3位时钟序列 + 7bit机器 + 12bit序列号 96 | 97 | ![](media/content-base64.png?raw=true) 98 | ![](media/algorithm.png?raw=true) 99 | 100 | 101 | 102 | ## 设计思路 103 | 104 | - 如上图,将原本10位的机器码拆分成3位时钟序列及7位机器码 105 | - 发生时间回拨的时候,时间已经发生了变化,那么这时将时钟序列新增1位,重新定义整个雪花Id 106 | - 为了避免实例重启引起时间序列丢失,因此时钟序列最好通过DB/缓存等方式存储起来 107 | 108 | ## 算法支持 109 | 110 | - 还是支持最长 69 年多的运行时间 111 | - 分布式实例规模由2^10(1024)降至2^7(128) 112 | - 单实例每毫秒仍然支持 4096次请求 113 | - 每个分布式实例支持最多 2^3(8) 次时间回拨 114 | 115 | ## 关键实现代码 116 | - [点击跳转代码位置](https://github.com/Bryan-Cyf/ClockSnowFlake/blob/master/ClockSnowFlake/src/Tools.SnowFlake/Ids/ClockSnowflakeId.cs) 117 | 118 | ## 更多示例 119 | 120 | 1. 查看 [使用例子](https://github.com/Bryan-Cyf/ClockSnowFlake/tree/master/sample) 121 | 2. 查看 [测试用例](https://github.com/Bryan-Cyf/ClockSnowFlake/tree/master/test) 122 | 123 | -------------------------------------------------------------------------------- /build/nuget.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1.1.0 4 | 0 5 | $(VersionPrefix).$(VersionSuffix) 6 | $(VersionPrefix).0 7 | $(NoWarn);CS1591 8 | Bryan 9 | Bryan 10 | ClockSnowFlake 11 | https://github.com/Bryan-Cyf/ClockSnowFlake 12 | True 13 | nuget-icon.png 14 | 15 | 16 | -------------------------------------------------------------------------------- /media/algorithm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Bryan-Cyf/ClockSnowFlake/7c4a5244b01bce260665dbc93c59f3a01494e03f/media/algorithm.png -------------------------------------------------------------------------------- /media/nuget-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Bryan-Cyf/ClockSnowFlake/7c4a5244b01bce260665dbc93c59f3a01494e03f/media/nuget-icon.png -------------------------------------------------------------------------------- /sample/ClockSnowFlake.Demo.WebApi/ClockSnowFlake.Demo.WebApi.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /sample/ClockSnowFlake.Demo.WebApi/Controllers/SnowFlakeController.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Bryan-Cyf/ClockSnowFlake/7c4a5244b01bce260665dbc93c59f3a01494e03f/sample/ClockSnowFlake.Demo.WebApi/Controllers/SnowFlakeController.cs -------------------------------------------------------------------------------- /sample/ClockSnowFlake.Demo.WebApi/Program.cs: -------------------------------------------------------------------------------- 1 | var builder = WebApplication.CreateBuilder(args); 2 | 3 | // Add services to the container. 4 | var config = builder.Configuration; 5 | 6 | builder.Services.AddControllers(); 7 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 8 | builder.Services.AddEndpointsApiExplorer(); 9 | builder.Services.AddSwaggerGen(); 10 | builder.Services.AddSnowFlakeId(config); 11 | 12 | var app = builder.Build(); 13 | 14 | // Configure the HTTP request pipeline. 15 | if (app.Environment.IsDevelopment()) 16 | { 17 | app.UseSwagger(); 18 | app.UseSwaggerUI(); 19 | } 20 | 21 | app.UseHttpsRedirection(); 22 | 23 | app.UseAuthorization(); 24 | 25 | app.MapControllers(); 26 | 27 | app.Run(); 28 | -------------------------------------------------------------------------------- /sample/ClockSnowFlake.Demo.WebApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*", 9 | 10 | "SnowFlakeId": { 11 | "WorkId": 2 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/ClockSnowFlake/ClockSnowFlake.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | netstandard2.1 6 | ClockSnowFlake 7 | [ID]Snowflake 8 | core,snowflake 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/ClockSnowFlake/Extensions/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Primitives; 5 | using ClockSnowFlake; 6 | 7 | namespace Microsoft.Extensions.DependencyInjection 8 | { 9 | public static class ServiceCollectionExtensions 10 | { 11 | public static IServiceCollection AddSnowFlakeId(this IServiceCollection services, IConfiguration configuration, Action configure = null, string sectionName = null) 12 | { 13 | sectionName ??= SnowFakeOptions.SectionName; 14 | services.AddOptions(); 15 | services.PostConfigure(x => 16 | { 17 | configure?.Invoke(x); 18 | }); 19 | var options = configuration.GetSection(sectionName).Get() ?? new SnowFakeOptions(); 20 | configure?.Invoke(options); 21 | SnowFakeOptionsConst.WorkId = options.WorkId; 22 | Console.WriteLine($"SnowWorkId:{SnowFakeOptionsConst.WorkId}"); 23 | return services; 24 | } 25 | 26 | public static IServiceCollection AddSnowFlakeId(this IServiceCollection services, Action configure) 27 | { 28 | services.AddOptions().Configure(configure); 29 | 30 | var options = new SnowFakeOptions(); 31 | configure.Invoke(options); 32 | 33 | SnowFakeOptionsConst.WorkId = options.WorkId; 34 | Console.WriteLine($"SnowWorkId:{SnowFakeOptionsConst.WorkId}"); 35 | return services; 36 | } 37 | 38 | public static void AddSnowFlakeId(this IConfiguration configuration, Action configure = null, string sectionName = null) 39 | { 40 | sectionName ??= SnowFakeOptions.SectionName; 41 | var options = configuration.GetSection(sectionName).Get() ?? new SnowFakeOptions(); 42 | configure?.Invoke(options); 43 | SnowFakeOptionsConst.WorkId = options.WorkId; 44 | Console.WriteLine($"SnowWorkId:{SnowFakeOptionsConst.WorkId}"); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/ClockSnowFlake/Generator/ClockSnowFlakeIdGenerator.cs: -------------------------------------------------------------------------------- 1 | namespace ClockSnowFlake 2 | { 3 | /// 4 | /// 基于时钟序列的 雪花算法ID 生成器 5 | /// 6 | public class ClockSnowFlakeIdGenerator : ILongGenerator 7 | { 8 | public ClockSnowFlakeIdGenerator() 9 | { 10 | var workerId = SnowFakeOptionsConst.WorkId; 11 | _id = new ClockSnowflakeId(workerId); 12 | } 13 | 14 | /// 15 | /// 基于时钟序列的雪花算法ID 16 | /// 17 | private readonly ClockSnowflakeId _id; 18 | 19 | /// 20 | /// 获取类型的实例 21 | /// 22 | public static ClockSnowFlakeIdGenerator Current { get; set; } = new ClockSnowFlakeIdGenerator(); 23 | 24 | /// 25 | /// 创建ID 26 | /// 27 | /// 28 | public long Create() 29 | { 30 | return _id.NextId(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/ClockSnowFlake/Generator/IIdGenerator.cs: -------------------------------------------------------------------------------- 1 | namespace ClockSnowFlake 2 | { 3 | /// 4 | /// ID 生成器 5 | /// 6 | /// 数据类型 7 | public interface IIdGenerator 8 | { 9 | /// 10 | /// 创建 ID 11 | /// 12 | /// 13 | T Create(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/ClockSnowFlake/Generator/ILongGenerator.cs: -------------------------------------------------------------------------------- 1 | namespace ClockSnowFlake 2 | { 3 | /// 4 | /// Long Id 生成器 5 | /// 6 | public interface ILongGenerator : IIdGenerator 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/ClockSnowFlake/Helpers/SnowflakeHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Net; 4 | using System.Net.Sockets; 5 | 6 | namespace ClockSnowFlake 7 | { 8 | internal class SnowflakeHelper 9 | { 10 | /// 11 | /// 获取随机工作Id 12 | /// 13 | /// 14 | public static long GetRandomWorkerId(long maxWorkerId) 15 | { 16 | //long? workerId = Math.Abs(Environment.MachineName.GetHashCode()) % maxWorkerId; 17 | var workerId = GetLastIpNum(); 18 | 19 | if (workerId == null) 20 | { 21 | /** 22 | * 本系统SnowflakeIdWorker的workerId范围为0-1023,ip最后一段数字最大为255 23 | * 一旦获取本机ip失败,就取300-1023之间的随机数做为workerId 24 | */ 25 | workerId = CreateNumber(300, (int)(maxWorkerId % int.MaxValue)); 26 | } 27 | 28 | return workerId.Value; 29 | } 30 | 31 | /// 32 | /// 生成固定范围的随机数 33 | /// 34 | private static int CreateNumber(int min, int max) 35 | { 36 | Random random = new Random(); 37 | return random.Next(max) % (max - min + 1) + min; 38 | } 39 | 40 | /// 41 | /// 获取ip串中最后的数字 42 | /// 43 | private static long? GetLastIpNum() 44 | { 45 | string ip = ""; 46 | 47 | try 48 | { 49 | ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList.First(x => x.AddressFamily == AddressFamily.InterNetwork).ToString(); 50 | } 51 | catch 52 | { 53 | 54 | } 55 | 56 | if (ip == "") 57 | { 58 | return null; 59 | } 60 | 61 | 62 | string lastNum = ip.Substring(ip.LastIndexOf('.') + 1); 63 | return long.Parse(lastNum); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/ClockSnowFlake/IdGener.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ClockSnowFlake 4 | { 5 | /// 6 | /// Id 生成器 7 | /// 8 | public static class IdGener 9 | { 10 | /// 11 | ///基于时钟序列的 Long 生成器 12 | /// 13 | public static ILongGenerator ClockLongGenerator { get; set; } = ClockSnowFlakeIdGenerator.Current; 14 | 15 | /// 16 | /// 用Guid创建标识 17 | /// 18 | /// 19 | public static string GetGuid() 20 | { 21 | return Guid.NewGuid().ToString("N"); 22 | } 23 | 24 | /// 25 | /// 创建 Long ID 26 | /// 27 | /// 28 | public static long GetLong() 29 | { 30 | return ClockLongGenerator.Create(); 31 | } 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/ClockSnowFlake/Ids/ClockSnowflakeId.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ClockSnowFlake 4 | { 5 | /// 6 | /// 基于时钟序列的雪花算法 7 | /// 64位唯一Id(由41位的timestamp + 3位时钟序列 + 7位自定义的机器码 + 13位累加计数器组成) 8 | /// 9 | public class ClockSnowflakeId 10 | { 11 | /// 12 | /// 基准时间 13 | /// 14 | public const long TWEPOCH = 1288834974657L; 15 | 16 | /// 17 | /// 机器标识位数 18 | /// 19 | private const int WORKER_ID_BITS = 7; 20 | 21 | /// 22 | /// 时钟序列标识位数 23 | /// 24 | private const int CLOCK_ID_BITS = 3; 25 | 26 | /// 27 | /// 序列号标识位数 28 | /// 29 | private const int SEQUENCE_BITS = 12; 30 | 31 | /// 32 | /// 机器ID最大值 33 | /// 34 | private const long MAX_WORKER_ID = -1L ^ (-1L << WORKER_ID_BITS); 35 | 36 | /// 37 | /// 时钟序列最大值 38 | /// 39 | private const long CLOCK_SEQUENCE_MASK = -1L ^ (-1L << CLOCK_ID_BITS); 40 | 41 | /// 42 | /// 序列号ID最大值 43 | /// 44 | private const long SEQUENCE_MASK = -1L ^ (-1L << SEQUENCE_BITS); 45 | 46 | /// 47 | /// 机器ID偏左移12位 48 | /// 49 | private const int WORKER_ID_SHIFT = SEQUENCE_BITS; 50 | 51 | /// 52 | /// 时钟序列偏左移19位 53 | /// 54 | private const int CLOCK_SEQUENCE_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS; 55 | 56 | /// 57 | /// 时间毫秒左移22位 58 | /// 59 | private const int TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + CLOCK_ID_BITS; 60 | 61 | /// 62 | /// 时间序列 63 | /// 64 | private long _clockSequence = 0L; 65 | 66 | /// 67 | /// 序列号ID 68 | /// 69 | private long _sequence = 0L; 70 | 71 | /// 72 | /// 最后时间戳 73 | /// 74 | private long _lastTimestamp = -1L; 75 | 76 | /// 77 | /// 机器ID 78 | /// 79 | public long WorkerId { get; protected set; } 80 | 81 | /// 82 | /// 序列号ID 83 | /// 84 | public long Sequence 85 | { 86 | get => _sequence; 87 | internal set => _sequence = value; 88 | } 89 | 90 | /// 91 | /// 初始化一个类型的实例 92 | /// 93 | /// 机器ID 94 | /// 序列号ID 95 | public ClockSnowflakeId(long? workerId, long sequence = 0L) 96 | { 97 | if (workerId == null) 98 | { 99 | //如果没配置,则采用随机工作Id 100 | workerId = SnowflakeHelper.GetRandomWorkerId(MAX_WORKER_ID); 101 | } 102 | // 如果超出范围就抛出异常 103 | if (workerId > MAX_WORKER_ID || workerId < 0) 104 | { 105 | throw new ArgumentException($"worker Id 必须大于0,且不能大于 MaxWorkerId:{MAX_WORKER_ID}"); 106 | } 107 | 108 | // 先校验再赋值 109 | WorkerId = workerId.Value; 110 | _sequence = sequence; 111 | } 112 | 113 | /// 114 | /// 对象锁 115 | /// 116 | private readonly object _lock = new object(); 117 | 118 | /// 119 | /// 获取下一个ID 120 | /// 121 | /// 122 | public long NextId() 123 | { 124 | lock (_lock) 125 | { 126 | //当前系统时间戳 127 | var currentTimestamp = TimeGen(); 128 | //出现时间回拨 当前系统时间小于最后更新时间 129 | if (currentTimestamp < _lastTimestamp) 130 | { 131 | // _clockSequence自增,和CLOCK_SEQUENCE_MASK相与一下,去掉高位 132 | _clockSequence = (_clockSequence + 1) & CLOCK_SEQUENCE_MASK; 133 | } 134 | 135 | // 如果上次生成时间和当前时间相同,在同一毫秒内 136 | if (_lastTimestamp == currentTimestamp) 137 | { 138 | // sequence自增,和SEQUENCE_MASK相与一下,去掉高位 139 | _sequence = (_sequence + 1) & SEQUENCE_MASK; 140 | //判断是否溢出,也就是每毫秒内超过1024,当为1024时,与sequenceMask相与,sequence就等于0 141 | if (_sequence == 0) 142 | { 143 | //等待到下一毫秒 144 | currentTimestamp = TilNextMillis(_lastTimestamp); 145 | } 146 | } 147 | else 148 | { 149 | //如果和上次生成时间不同,重置sequence,就是下一毫秒开始,sequence计数重新从0开始累加, 150 | _sequence = 0; 151 | } 152 | 153 | _lastTimestamp = currentTimestamp; 154 | return ((currentTimestamp - TWEPOCH) << TIMESTAMP_LEFT_SHIFT) | _clockSequence << CLOCK_SEQUENCE_SHIFT | (WorkerId << WORKER_ID_SHIFT) | _sequence; 155 | } 156 | } 157 | 158 | /// 159 | /// 获取增量时间戳,防止产生的时间比之前的时间还要小(由于NTP回拨等问题),保持增量的趋势 160 | /// 161 | /// 最后一个时间戳 162 | /// 163 | protected virtual long TilNextMillis(long lastTimestamp) 164 | { 165 | var timestamp = TimeGen(); 166 | while (timestamp <= lastTimestamp) 167 | { 168 | timestamp = TimeGen(); 169 | } 170 | 171 | return timestamp; 172 | } 173 | 174 | /// 175 | /// 获取当前时间戳 176 | /// 177 | /// 178 | protected virtual long TimeGen() 179 | { 180 | return CurrentTimeMills(); 181 | } 182 | 183 | /// 184 | /// 获取当前时间戳 185 | /// 186 | public static Func CurrentTimeFunc = InternalCurrentTimeMillis; 187 | 188 | /// 189 | /// 获取当前时间戳 190 | /// 191 | /// 192 | public static long CurrentTimeMills() 193 | { 194 | return CurrentTimeFunc(); 195 | } 196 | 197 | /// 198 | /// 重置当前时间戳 199 | /// 200 | /// 201 | /// 202 | public static IDisposable StubCurrentTime(Func func) 203 | { 204 | CurrentTimeFunc = func; 205 | return new DisposableAction(() => { CurrentTimeFunc = InternalCurrentTimeMillis; }); 206 | } 207 | 208 | /// 209 | /// 重置当前时间戳 210 | /// 211 | /// 212 | /// 213 | public static IDisposable StubCurrentTime(long millis) 214 | { 215 | CurrentTimeFunc = () => millis; 216 | return new DisposableAction(() => { CurrentTimeFunc = InternalCurrentTimeMillis; }); 217 | } 218 | 219 | private static readonly DateTime Jan1St1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); 220 | 221 | /// 222 | /// 默认当前时间戳 223 | /// 224 | /// 225 | private static long InternalCurrentTimeMillis() 226 | { 227 | return (long)(DateTime.UtcNow - Jan1St1970).TotalMilliseconds; 228 | } 229 | 230 | /// 231 | /// 一次性方法 232 | /// 233 | public class DisposableAction : IDisposable 234 | { 235 | /// 236 | /// 执行方法 237 | /// 238 | private readonly Action _action; 239 | 240 | /// 241 | /// 初始化一个类型的实例 242 | /// 243 | /// 执行方法 244 | public DisposableAction(Action action) 245 | { 246 | _action = action ?? throw new ArgumentNullException(nameof(action)); 247 | } 248 | 249 | /// 250 | /// 释放资源 251 | /// 252 | public void Dispose() 253 | { 254 | _action(); 255 | } 256 | } 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /src/ClockSnowFlake/Options/SnowFakeOptionsConst.cs: -------------------------------------------------------------------------------- 1 | namespace ClockSnowFlake 2 | { 3 | public class SnowFakeOptionsConst 4 | { 5 | /// 6 | /// 工作节点ID,范围 0~128 7 | /// 8 | public static long? WorkId { get; set; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/ClockSnowFlake/Options/SnowFlakeOptions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Options; 2 | 3 | namespace ClockSnowFlake 4 | { 5 | public class SnowFakeOptions 6 | { 7 | public const string SectionName = "SnowFlakeId"; 8 | 9 | /// 10 | /// 工作节点ID,范围 0~128 11 | /// 12 | public int? WorkId { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /test/ClockSnowFlake.Unitests/ClockSnowFlake.Unitests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | net6.0 4 | false 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | all 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /test/ClockSnowFlake.Unitests/ClockSnowFlakeTest.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Xunit; 4 | 5 | namespace ClockSnowFlake.Unitests 6 | { 7 | public class ClockSnowFlakeTest 8 | { 9 | 10 | public ClockSnowFlakeTest() 11 | { 12 | IServiceCollection services = new ServiceCollection(); 13 | //注意:工作机器ID不能重复 14 | services.AddSnowFlakeId(x => x.WorkId = 2); 15 | } 16 | 17 | [Fact] 18 | public void Id_Generate_Should_Be_Succeed() 19 | { 20 | var id = IdGener.GetLong(); 21 | Assert.True(id > 0); 22 | } 23 | } 24 | } 25 | --------------------------------------------------------------------------------