├── .gitattributes ├── .github └── workflows │ └── build.yml ├── .gitignore ├── LICENSE ├── README.md ├── build.ps1 ├── default.ps1 └── src ├── redislock-cs.test ├── MultiServerLockTests.cs ├── SingleServerLockTests.cs ├── app.json └── redislock-cs.test.csproj ├── redlock-cs.sln └── redlock-cs ├── .vs └── redlock-cs │ └── v15 │ └── Server │ └── sqlite3 │ ├── db.lock │ └── storage.ide ├── Lock.cs ├── Redlock.cs └── redlock-cs.csproj /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | 9 | jobs: 10 | build: 11 | name: Build 12 | runs-on: windows-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | with: 16 | fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis 17 | - name: Set up JDK 11 18 | uses: actions/setup-java@v1 19 | with: 20 | java-version: 1.11 21 | - name: Cache SonarQube packages 22 | uses: actions/cache@v1 23 | with: 24 | path: ~\sonar\cache 25 | key: ${{ runner.os }}-sonar 26 | restore-keys: ${{ runner.os }}-sonar 27 | - name: Cache SonarQube scanner 28 | id: cache-sonar-scanner 29 | uses: actions/cache@v1 30 | with: 31 | path: .\.sonar\scanner 32 | key: ${{ runner.os }}-sonar-scanner 33 | restore-keys: ${{ runner.os }}-sonar-scanner 34 | - name: Install SonarQube scanner 35 | if: steps.cache-sonar-scanner.outputs.cache-hit != 'true' 36 | shell: powershell 37 | run: | 38 | New-Item -Path .\.sonar\scanner -ItemType Directory 39 | dotnet tool update dotnet-sonarscanner --tool-path .\.sonar\scanner 40 | - name: Build and analyze 41 | env: 42 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any 43 | shell: powershell 44 | run: | 45 | .\.sonar\scanner\dotnet-sonarscanner begin /k:"KidFashion_redlock-cs_AYdyOFQqUyjwEBOBx4mr" /d:sonar.token="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="${{ secrets.SONAR_HOST_URL }}" 46 | dotnet build 47 | .\.sonar\scanner\dotnet-sonarscanner end /d:sonar.token="${{ secrets.SONAR_TOKEN }}" 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.sln.docstates 8 | 9 | # Build results 10 | [Dd]ebug/ 11 | [Dd]ebugPublic/ 12 | [Rr]elease/ 13 | [Rr]eleases/ 14 | x64/ 15 | x86/ 16 | build/ 17 | bld/ 18 | [Bb]in/ 19 | [Oo]bj/ 20 | 21 | # Roslyn cache directories 22 | *.ide/ 23 | 24 | # MSTest test Results 25 | [Tt]est[Rr]esult*/ 26 | [Bb]uild[Ll]og.* 27 | 28 | #NUNIT 29 | *.VisualState.xml 30 | TestResult.xml 31 | 32 | # Build Results of an ATL Project 33 | [Dd]ebugPS/ 34 | [Rr]eleasePS/ 35 | dlldata.c 36 | 37 | *_i.c 38 | *_p.c 39 | *_i.h 40 | *.ilk 41 | *.meta 42 | *.obj 43 | *.pch 44 | *.pdb 45 | *.pgc 46 | *.pgd 47 | *.rsp 48 | *.sbr 49 | *.tlb 50 | *.tli 51 | *.tlh 52 | *.tmp 53 | *.tmp_proj 54 | *.log 55 | *.vspscc 56 | *.vssscc 57 | .builds 58 | *.pidb 59 | *.svclog 60 | *.scc 61 | 62 | # Chutzpah Test files 63 | _Chutzpah* 64 | 65 | # Visual C++ cache files 66 | ipch/ 67 | *.aps 68 | *.ncb 69 | *.opensdf 70 | *.sdf 71 | *.cachefile 72 | 73 | # Visual Studio profiler 74 | *.psess 75 | *.vsp 76 | *.vspx 77 | 78 | # TFS 2012 Local Workspace 79 | $tf/ 80 | 81 | # Guidance Automation Toolkit 82 | *.gpState 83 | 84 | # ReSharper is a .NET coding add-in 85 | _ReSharper*/ 86 | *.[Rr]e[Ss]harper 87 | *.DotSettings.user 88 | 89 | # JustCode is a .NET coding addin-in 90 | .JustCode 91 | 92 | # TeamCity is a build add-in 93 | _TeamCity* 94 | 95 | # DotCover is a Code Coverage Tool 96 | *.dotCover 97 | 98 | # NCrunch 99 | _NCrunch_* 100 | .*crunch*.local.xml 101 | 102 | # MightyMoose 103 | *.mm.* 104 | AutoTest.Net/ 105 | 106 | # Web workbench (sass) 107 | .sass-cache/ 108 | 109 | # Installshield output folder 110 | [Ee]xpress/ 111 | 112 | # DocProject is a documentation generator add-in 113 | DocProject/buildhelp/ 114 | DocProject/Help/*.HxT 115 | DocProject/Help/*.HxC 116 | DocProject/Help/*.hhc 117 | DocProject/Help/*.hhk 118 | DocProject/Help/*.hhp 119 | DocProject/Help/Html2 120 | DocProject/Help/html 121 | 122 | # Click-Once directory 123 | publish/ 124 | 125 | # Publish Web Output 126 | *.[Pp]ublish.xml 127 | *.azurePubxml 128 | # TODO: Comment the next line if you want to checkin your web deploy settings 129 | # but database connection strings (with potential passwords) will be unencrypted 130 | *.pubxml 131 | *.publishproj 132 | 133 | # NuGet Packages 134 | *.nupkg 135 | # The packages folder can be ignored because of Package Restore 136 | **/packages/* 137 | # except build/, which is used as an MSBuild target. 138 | !**/packages/build/ 139 | # If using the old MSBuild-Integrated Package Restore, uncomment this: 140 | #!**/packages/repositories.config 141 | 142 | # Windows Azure Build Output 143 | csx/ 144 | *.build.csdef 145 | 146 | # Windows Store app package directory 147 | AppPackages/ 148 | 149 | # Others 150 | sql/ 151 | *.Cache 152 | ClientBin/ 153 | [Ss]tyle[Cc]op.* 154 | ~$* 155 | *~ 156 | *.dbmdl 157 | *.dbproj.schemaview 158 | *.pfx 159 | *.publishsettings 160 | node_modules/ 161 | 162 | # RIA/Silverlight projects 163 | Generated_Code/ 164 | 165 | # Backup & report files from converting an old project file 166 | # to a newer Visual Studio version. Backup files are not needed, 167 | # because we have git ;-) 168 | _UpgradeReport_Files/ 169 | Backup*/ 170 | UpgradeLog*.XML 171 | UpgradeLog*.htm 172 | 173 | # SQL Server files 174 | *.mdf 175 | *.ldf 176 | 177 | # Business Intelligence projects 178 | *.rdl.data 179 | *.bim.layout 180 | *.bim_*.settings 181 | 182 | # Microsoft Fakes 183 | FakesAssemblies/ 184 | 185 | #ApiKey 186 | apikey.txt -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | redlock-cs 2 | ========== 3 | 4 | [![Build status](https://ci.appveyor.com/api/projects/status/xat1stsmpvl3gjcg?svg=true)](https://ci.appveyor.com/project/KidFashion/redlock-cs) 5 | 6 | Distributed lock with Redis and C# (based on the [redlock algorithm](http://redis.io/topics/distlock)) 7 | 8 | Redlock-cs is available through nuget as [redlock-cs package](http://www.nuget.org/packages/redlock-cs/). 9 | 10 | ## Usage 11 | 12 | Check our [Unit Test](https://github.com/KidFashion/redlock-cs/blob/master/tests/MultiServerLockTests.cs). 13 | 14 | The API is based on antirez [Ruby implementation](https://github.com/antirez/redlock-rb) and works as in the following example: 15 | 16 | ```csharp 17 | // Declare a Distributed Lock based on 3 REDIS servers 18 | 19 | var dlm = new Redlock( 20 | ConnectionMultiplexer.Connect("127.0.0.1:6379"), 21 | ConnectionMultiplexer.Connect("127.0.0.1:6380"), 22 | ConnectionMultiplexer.Connect("127.0.0.1:6381") 23 | ); 24 | 25 | // Declare lock object. 26 | Lock lockObject; 27 | 28 | // Try to acquire the lock (with resourceName as lock identifier and an 29 | // expiration time of 10 seconds). 30 | var locked = dlm.Lock( 31 | resourceName, 32 | new TimeSpan(0, 0, 10), 33 | out lockObject 34 | ); 35 | 36 | // If locked is true, lockObject is populated and the lock has been acquired, 37 | // otherwise the lock has not been acquired. 38 | 39 | // Tries to release the lock contained in lockObject. 40 | dlm.Unlock(lockObject); 41 | ``` 42 | 43 | ## TODO 44 | 45 | * Disposable pattern. 46 | * Hide StackExchange.Redis library inside Redlock object. 47 | -------------------------------------------------------------------------------- /build.ps1: -------------------------------------------------------------------------------- 1 | Param( 2 | [String]$task = "Build-Project" 3 | ) 4 | 5 | Invoke-WebRequest https://github.com/psake/psake/raw/master/psake.psm1 -OutFile psake.psm1 6 | Import-Module .\psake.psm1 7 | 8 | Invoke-Psake $task -------------------------------------------------------------------------------- /default.ps1: -------------------------------------------------------------------------------- 1 | Properties { 2 | $script:hash = @{} 3 | $script:hash.build_mode = "Release" 4 | $solution = (ls *.sln).Name 5 | $packageName = [System.IO.Path]::GetFileNameWithoutExtension((ls *.sln)) 6 | # Test 7 | $testPrj = "..\..\tests\" 8 | 9 | # Directories 10 | # Directory of output binaries (output of Visual Studio) 11 | $outdir = if (test-path env:CCNetArtifactDirectory) {[System.String]::Concat((ls env:CCNetArtifactDirectory).Value,"\Staging\\")} else {[System.String]::Concat((pwd),"\Staging\\")} 12 | $artifactdir = [System.String]::Concat((pwd),"\Artifacts\") 13 | $deployPackageDir = (join-path $outdir "..\DeployPackage") 14 | } 15 | 16 | Task default -depends Print-TaskList 17 | 18 | Task setConfiguration-Debug { 19 | $script:hash.build_mode = "Debug" 20 | } 21 | 22 | Task setConfiguration-Release { 23 | $script:hash.build_mode = "Release" 24 | } 25 | 26 | Task Print-Banner { 27 | Write-Host -ForegroundColor Yellow "=============================================" 28 | Write-Host -ForegroundColor Yellow "Project: Redlock-cs" 29 | Write-Host -ForegroundColor Yellow "Distributed lock with Redis and C#" 30 | Write-Host -ForegroundColor Yellow "Author: Angelo Simone Scotto" 31 | Write-Host -ForegroundColor Yellow "Url: https://github.com/KidFashion/redlock-cs" 32 | Write-Host -ForegroundColor Yellow "=============================================" 33 | 34 | } 35 | 36 | Task Print-TaskList -depends Print-Banner { 37 | Write-Host -ForegroundColor White "List of Available Tasks:" 38 | Write-Host -ForegroundColor Green "Print-TaskList" -nonewline;Write-Host " : Print these instructions." 39 | #Write-Host -ForegroundColor Green "Build-Solution"-nonewline; write-host " : Build Project (4.5)" 40 | #Write-Host -ForegroundColor Green "Build-Solution-net40"-nonewline; write-host " : Build Project (4.0)" 41 | 42 | 43 | Write-Host -ForegroundColor Green "Build-Project"-nonewline; write-host " : Build Project (4.5)" 44 | #Write-Host -ForegroundColor Green "Build-Project-Net45"-nonewline; write-host " : Build Project (4.5)" 45 | Write-Host -ForegroundColor Green "Build-Project-Net40"-nonewline; write-host " : Build Project (4.0)" 46 | Write-Host -ForegroundColor Green "Test-Project" -nonewline; write-host " : Test Project (v4.5)" 47 | Write-Host -ForegroundColor Green "Measure-CodeCoverage" -nonewline; write-host " : Generate code coverage report." 48 | Write-Host -ForegroundColor Green "Generate-Reports" -nonewline; write-host " : Generate UnitTest and CodeCoverage reports." 49 | 50 | Write-Host -ForegroundColor Green "Package-Project" -nonewline; write-host " : Package Project in Nuget Package" 51 | } 52 | 53 | 54 | #Task Generate-Reports -depends Test-Solution, Measure-CodeCoverage { 55 | #} 56 | 57 | Task Build-Project -depends Build-Project-Net45 { 58 | } 59 | 60 | Task Build-Project-Net45 { 61 | $configuration = $script:hash.build_mode 62 | $version ="v4.5" 63 | $folder = ".\src" 64 | push-location $folder 65 | $itemToBuild = ls -Filter *.csproj | where {$_.Name -match ".*\."+$version+".csproj"} 66 | if ($itemToBuild -eq $null) {$itemToBuild = ls *.csproj | where {$_.Name -notmatch ".*\.v\d\.\d\.csproj"}} 67 | Write-Host "Building Project ($($itemToBuild.Name))" -ForegroundColor Green 68 | Exec { msbuild $itemToBuild /t:Rebuild /p:"TargetFrameworkVersion=$version;Configuration=$configuration" /v:quiet /p:OutDir=$outdir/$version} 69 | pop-location 70 | } 71 | 72 | Task Build-Project-Net40 { 73 | $configuration = $script:hash.build_mode 74 | $version ="v4.0" 75 | $folder = ".\src" 76 | push-location $folder 77 | $itemToBuild = ls -Filter *.csproj | where {$_.Name -match ".*\."+$version+".csproj"} 78 | if ($itemToBuild -eq $null) {$itemToBuild = ls *.csproj | where {$_.Name -notmatch ".*\.v\d\.\d\.csproj"}} 79 | Write-Host "Building Project ($($itemToBuild.Name))" -ForegroundColor Green 80 | Exec { msbuild $itemToBuild /t:Rebuild /p:"TargetFrameworkVersion=$version;Configuration=$configuration" /v:quiet /p:OutDir=$outdir/$version} 81 | pop-location 82 | } 83 | 84 | Task Build-Test-Project-Net45 { 85 | $version ="v4.5" 86 | $folder = ".\tests" 87 | $configuration = $script:hash.build_mode 88 | push-location $folder 89 | 90 | $itemToBuild = ls *.csproj | where {$_.Name -match ".*\."+$version+".csproj"} 91 | if ($itemToBuild -eq $null) {$itemToBuild = ls *.csproj | where {$_.Name -notmatch ".*\.v\d\.\d\.csproj"}} 92 | Write-Host "Building Project ($($itemToBuild.Name))" -ForegroundColor Green 93 | Exec { msbuild $itemToBuild /t:Rebuild /p:"TargetFrameworkVersion=$version;Configuration=$configuration" /v:quiet /p:OutDir=$outdir/$version} 94 | pop-location 95 | } 96 | 97 | Task Test-Project -depends Test-Project-Net45 { 98 | } 99 | 100 | Task Test-Project-Net45 -depends Build-Test-Project-Net45 { 101 | $version = "v4.5" 102 | $configuration = $script:hash.build_mode 103 | $gallio = (ls ".\packages\GallioBundle*\bin\Gallio.Echo.exe").FullName 104 | $ServiceTestDll = "Redlock.CSharp.Tests.dll" 105 | #Add-PSSnapIn Gallio 106 | #Run-Gallio "Staging\$($version)\$($ServiceTestDll)" -Filter "exclude Category:database" -rd "Staging\$($version)\reports" -rt html -ReportNameFormat "test-report" 107 | &$gallio "Staging\$($version)\$($ServiceTestDll)" /f:"exclude Category:database" "/rd:Staging\$($version)\reports" /rt:html /rnf:"test-report" 108 | 109 | Write-Host "UnitTest Report Generated in Staging\$($version)\reports\test-report.html" -ForegroundColor Green 110 | 111 | } 112 | 113 | 114 | Task Create-NugetPackage -depends Build-Project-Net45, Build-Project-Net40 { 115 | if (test-path nuget) {rm -force -recurse nuget} 116 | mkdir nuget 117 | $nuget = (ls ".\packages\NuGet.CommandLine*\tools\nuget.exe").FullName 118 | &$nuget pack redlock-cs.nuspec -outputdirectory nuget 119 | } 120 | 121 | Task Publish-NugetPackage -depends Create-NugetPackage { 122 | $apikey = cat apikey.txt 123 | $nuget = (ls ".\packages\NuGet.CommandLine*\tools\nuget.exe").FullName 124 | $packagetopublish = ls nuget\*.nupkg 125 | &$nuget push $packagetopublish -apikey $apikey 126 | } 127 | 128 | Task Build-Solution -depends setConfiguration-Release, Build-Project { 129 | } 130 | -------------------------------------------------------------------------------- /src/redislock-cs.test/MultiServerLockTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | using NUnit.Framework; 8 | using Microsoft.Extensions.Configuration; 9 | 10 | using Redlock.CSharp; 11 | using StackExchange.Redis; 12 | using System.Diagnostics; 13 | 14 | namespace Redlock.CSharp.Tests 15 | { 16 | [TestFixture] 17 | public class MultiServerLockTests 18 | { 19 | private const string resourceName = "MyResourceName"; 20 | private const string ServerA_Key = "ConnectionString_ServerA"; 21 | private const string ServerB_Key = "ConnectionString_ServerB"; 22 | private const string ServerC_Key = "ConnectionString_ServerC"; 23 | 24 | #if TOREMOVE 25 | //contains list of processes for teardown 26 | private List redisProcessList = new List(); 27 | 28 | 29 | // Since redis on windows is abandoned, tests should only invoke a linux instance somewhere (we need three instances). 30 | [OneTimeSetUp] 31 | public void setup() 32 | { 33 | // Launch Server 34 | Process redis = new Process(); 35 | 36 | // Configure the process using the StartInfo properties. 37 | redis.StartInfo.FileName = System.IO.Path.GetFullPath(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"..\..\..\packages\Redis-32.2.6.12.1\tools\redis-server.exe"); 38 | redis.StartInfo.Arguments = "--port 6379"; 39 | redis.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 40 | redis.Start(); 41 | redisProcessList.Add(redis); 42 | 43 | redis = new Process(); 44 | 45 | // Configure the process using the StartInfo properties. 46 | redis.StartInfo.FileName = System.IO.Path.GetFullPath(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"..\..\..\packages\Redis-32.2.6.12.1\tools\redis-server.exe"); 47 | redis.StartInfo.Arguments = "--port 6380"; 48 | redis.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 49 | redis.Start(); 50 | redisProcessList.Add(redis); 51 | 52 | redis = new Process(); 53 | 54 | // Configure the process using the StartInfo properties. 55 | redis.StartInfo.FileName = System.IO.Path.GetFullPath(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"..\..\..\packages\Redis-32.2.6.12.1\tools\redis-server.exe"); 56 | redis.StartInfo.Arguments = "--port 6381"; 57 | redis.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 58 | redis.Start(); 59 | 60 | redisProcessList.Add(redis); 61 | } 62 | 63 | // Since redis on windows is abandoned, tests should only invoke a linux instance somewhere (we need three instances). 64 | [OneTimeTearDown] 65 | public void teardown() 66 | { 67 | foreach (var process in redisProcessList) 68 | { 69 | if (!process.HasExited) process.Kill(); 70 | } 71 | 72 | redisProcessList.Clear(); 73 | } 74 | #endif 75 | [Test] 76 | public void TestWhenLockedAnotherLockRequestIsRejected() 77 | { 78 | var configBuilder = new ConfigurationBuilder(); 79 | configBuilder 80 | .AddJsonFile("app.json", true); 81 | var configRoot = configBuilder.Build(); 82 | 83 | var dlm = new Redlock(ConnectionMultiplexer.Connect(configRoot[ServerA_Key]), ConnectionMultiplexer.Connect(configRoot[ServerB_Key]), ConnectionMultiplexer.Connect(configRoot[ServerC_Key])); 84 | 85 | Lock lockObject; 86 | Lock newLockObject; 87 | 88 | var locked = dlm.Lock(resourceName, new TimeSpan(0, 0, 10), out lockObject); 89 | Assert.IsTrue(locked, "Unable to get lock"); 90 | locked = dlm.Lock(resourceName, new TimeSpan(0, 0, 10), out newLockObject); 91 | Assert.IsFalse(locked, "lock taken, it shouldn't be possible"); 92 | dlm.Unlock(lockObject); 93 | } 94 | 95 | [Test] 96 | public void TestThatSequenceLockedUnlockedAndLockedAgainIsSuccessfull() 97 | { 98 | var configBuilder = new ConfigurationBuilder(); 99 | configBuilder 100 | .AddJsonFile("app.json", true); 101 | var configRoot = configBuilder.Build(); 102 | 103 | var dlm = new Redlock(ConnectionMultiplexer.Connect(configRoot[ServerA_Key]), ConnectionMultiplexer.Connect(configRoot[ServerB_Key]), ConnectionMultiplexer.Connect(configRoot[ServerC_Key])); 104 | 105 | Lock lockObject = null; 106 | Lock newLockObject; 107 | 108 | var locked = dlm.Lock(resourceName, new TimeSpan(0, 0, 10), out lockObject); 109 | Assert.IsTrue(locked, "Unable to get lock"); 110 | dlm.Unlock(lockObject); 111 | locked = dlm.Lock(resourceName, new TimeSpan(0, 0, 10), out newLockObject); 112 | Assert.IsTrue(locked, "Unable to get lock"); 113 | 114 | dlm.Unlock(newLockObject); 115 | 116 | 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/redislock-cs.test/SingleServerLockTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | using NUnit.Framework; 8 | 9 | using Redlock.CSharp; 10 | using StackExchange.Redis; 11 | using System.Diagnostics; 12 | using System.IO; 13 | using Microsoft.Extensions.Configuration; 14 | 15 | namespace Redlock.CSharp.Tests 16 | { 17 | [TestFixture] 18 | public class SingleServerLockTests 19 | { 20 | private const string resourceName = "MyResourceName"; 21 | 22 | private const string ServerA_Key = "ConnectionString_ServerA"; 23 | 24 | #if TOBEREMOVED 25 | // 26 | private List redisProcessList = new List(); 27 | [OneTimeSetUp] 28 | public void setup() 29 | { 30 | // Launch Server 31 | Process redis = new Process(); 32 | 33 | // Configure the process using the StartInfo properties. 34 | redis.StartInfo.FileName = System.IO.Path.GetFullPath(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)+ @"..\..\..\packages\Redis-32.2.6.12.1\tools\redis-server.exe"); 35 | redis.StartInfo.Arguments = "--port 6379"; 36 | redis.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 37 | redis.Start(); 38 | 39 | redisProcessList.Add(redis); 40 | } 41 | 42 | [OneTimeTearDown] 43 | public void teardown() 44 | { 45 | foreach (var process in redisProcessList) 46 | { 47 | if (!process.HasExited) process.Kill(); 48 | } 49 | 50 | redisProcessList.Clear(); 51 | } 52 | #endif 53 | [Test] 54 | public void TestWhenLockedAnotherLockRequestIsRejected() 55 | { 56 | var configBuilder = new ConfigurationBuilder(); 57 | configBuilder 58 | .AddJsonFile("app.json", true); 59 | var configRoot = configBuilder.Build(); 60 | 61 | var dlm = new Redlock(ConnectionMultiplexer.Connect(configRoot[ServerA_Key])); 62 | 63 | Lock lockObject; 64 | Lock newLockObject; 65 | var locked = dlm.Lock(resourceName, new TimeSpan(0, 0, 10), out lockObject); 66 | Assert.IsTrue(locked, "Unable to get lock"); 67 | locked = dlm.Lock(resourceName, new TimeSpan(0, 0, 10), out newLockObject); 68 | Assert.IsFalse(locked, "lock taken, it shouldn't be possible"); 69 | dlm.Unlock(lockObject); 70 | } 71 | 72 | [Test] 73 | public void TestThatSequenceLockedUnlockedAndLockedAgainIsSuccessfull() 74 | { 75 | var configBuilder = new ConfigurationBuilder(); 76 | configBuilder 77 | .AddJsonFile("app.json", true); 78 | var configRoot = configBuilder.Build(); 79 | 80 | var dlm = new Redlock(ConnectionMultiplexer.Connect(configRoot[ServerA_Key])); 81 | 82 | Lock lockObject; 83 | Lock newLockObject; 84 | var locked = dlm.Lock(resourceName, new TimeSpan(0, 0, 10), out lockObject); 85 | Assert.IsTrue(locked, "Unable to get lock"); 86 | dlm.Unlock(lockObject); 87 | locked = dlm.Lock(resourceName, new TimeSpan(0, 0, 10), out newLockObject); 88 | Assert.IsTrue(locked, "Unable to get lock"); 89 | dlm.Unlock(newLockObject); 90 | } 91 | 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/redislock-cs.test/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionString_ServerA": "127.0.0.1:6379", 3 | "ConnectionString_ServerB": "127.0.0.1:6380", 4 | "ConnectionString_ServerC": "127.0.0.1:6381" 5 | 6 | } -------------------------------------------------------------------------------- /src/redislock-cs.test/redislock-cs.test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.1 5 | 6 | false 7 | 8 | Redlock.CSharp.Tests 9 | 10 | 11 | 12 | AnyCPU 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | System 31 | 32 | 33 | System.Data 34 | 35 | 36 | System.Xml 37 | 38 | 39 | 40 | 41 | 42 | Always 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /src/redlock-cs.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28307.136 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "redlock-cs", "redlock-cs\redlock-cs.csproj", "{EE173CFC-CC6F-49F7-AFB1-D887C238E8C1}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "redislock-cs.test", "redislock-cs.test\redislock-cs.test.csproj", "{950963BB-0C05-413B-8813-EC65FA7298C2}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {EE173CFC-CC6F-49F7-AFB1-D887C238E8C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {EE173CFC-CC6F-49F7-AFB1-D887C238E8C1}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {EE173CFC-CC6F-49F7-AFB1-D887C238E8C1}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {EE173CFC-CC6F-49F7-AFB1-D887C238E8C1}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {950963BB-0C05-413B-8813-EC65FA7298C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {950963BB-0C05-413B-8813-EC65FA7298C2}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {950963BB-0C05-413B-8813-EC65FA7298C2}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {950963BB-0C05-413B-8813-EC65FA7298C2}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {71765C42-C231-4E81-BC12-13776DD51EEB} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /src/redlock-cs/.vs/redlock-cs/v15/Server/sqlite3/db.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KidFashion/redlock-cs/9765a542f8a78edbf7b5c6e17729124895fbc786/src/redlock-cs/.vs/redlock-cs/v15/Server/sqlite3/db.lock -------------------------------------------------------------------------------- /src/redlock-cs/.vs/redlock-cs/v15/Server/sqlite3/storage.ide: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KidFashion/redlock-cs/9765a542f8a78edbf7b5c6e17729124895fbc786/src/redlock-cs/.vs/redlock-cs/v15/Server/sqlite3/storage.ide -------------------------------------------------------------------------------- /src/redlock-cs/Lock.cs: -------------------------------------------------------------------------------- 1 | #region LICENSE 2 | /* 3 | * Copyright 2014 Angelo Simone Scotto 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * */ 18 | #endregion 19 | 20 | using StackExchange.Redis; 21 | using System; 22 | using System.Collections.Generic; 23 | using System.Linq; 24 | using System.Text; 25 | using System.Threading.Tasks; 26 | 27 | namespace Redlock.CSharp 28 | { 29 | public class Lock 30 | { 31 | 32 | public Lock(RedisKey resource, RedisValue val, TimeSpan validity) 33 | { 34 | this.resource = resource; 35 | this.val = val ; 36 | this.validity_time = validity; 37 | } 38 | 39 | private RedisKey resource; 40 | 41 | private RedisValue val; 42 | 43 | private TimeSpan validity_time; 44 | 45 | public RedisKey Resource { get { return resource; } } 46 | 47 | public RedisValue Value { get { return val; } } 48 | 49 | public TimeSpan Validity { get { return validity_time; } } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/redlock-cs/Redlock.cs: -------------------------------------------------------------------------------- 1 | #region LICENSE 2 | /* 3 | * Copyright 2014 Angelo Simone Scotto 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * */ 18 | #endregion 19 | 20 | using StackExchange.Redis; 21 | using System; 22 | using System.Collections.Generic; 23 | using System.Linq; 24 | using System.Text; 25 | using System.Threading; 26 | using System.Threading.Tasks; 27 | 28 | namespace Redlock.CSharp 29 | { 30 | public class Redlock 31 | { 32 | 33 | public Redlock(params IConnectionMultiplexer[] list) 34 | { 35 | foreach(var item in list) 36 | this.redisMasterDictionary.Add(item.GetEndPoints().First().ToString(),item); 37 | } 38 | 39 | const int DefaultRetryCount = 3; 40 | readonly TimeSpan DefaultRetryDelay = new TimeSpan(0, 0, 0, 0, 200); 41 | const double ClockDriveFactor = 0.01; 42 | 43 | protected int Quorum { get { return (redisMasterDictionary.Count / 2) + 1; } } 44 | 45 | /// 46 | /// String containing the Lua unlock script. 47 | /// 48 | const String UnlockScript = @" 49 | if redis.call(""get"",KEYS[1]) == ARGV[1] then 50 | return redis.call(""del"",KEYS[1]) 51 | else 52 | return 0 53 | end"; 54 | 55 | 56 | protected static byte[] CreateUniqueLockId() 57 | { 58 | return Guid.NewGuid().ToByteArray(); 59 | } 60 | 61 | 62 | protected Dictionary redisMasterDictionary = new Dictionary(); 63 | 64 | //TODO: Refactor passing a ConnectionMultiplexer 65 | protected bool LockInstance(string redisServer, string resource, byte[] val, TimeSpan ttl) 66 | { 67 | 68 | bool succeeded; 69 | try 70 | { 71 | var redis = this.redisMasterDictionary[redisServer]; 72 | succeeded = redis.GetDatabase().StringSet(resource, val, ttl, When.NotExists); 73 | } 74 | catch (Exception) 75 | { 76 | succeeded = false; 77 | } 78 | return succeeded; 79 | } 80 | 81 | //TODO: Refactor passing a ConnectionMultiplexer 82 | protected void UnlockInstance(string redisServer, string resource, byte[] val) 83 | { 84 | RedisKey[] key = { resource }; 85 | RedisValue[] values = { val }; 86 | var redis = redisMasterDictionary[redisServer]; 87 | redis.GetDatabase().ScriptEvaluate( 88 | UnlockScript, 89 | key, 90 | values 91 | ); 92 | } 93 | 94 | public bool Lock(RedisKey resource, TimeSpan ttl, out Lock lockObject) 95 | { 96 | var val = CreateUniqueLockId(); 97 | Lock innerLock = null; 98 | bool successfull = retry(DefaultRetryCount, DefaultRetryDelay, () => 99 | { 100 | try 101 | { 102 | int n = 0; 103 | var startTime = DateTime.Now; 104 | 105 | // Use keys 106 | for_each_redis_registered( 107 | redis => 108 | { 109 | if (LockInstance(redis, resource, val, ttl)) n += 1; 110 | } 111 | ); 112 | 113 | /* 114 | * Add 2 milliseconds to the drift to account for Redis expires 115 | * precision, which is 1 millisecond, plus 1 millisecond min drift 116 | * for small TTLs. 117 | */ 118 | var drift = Convert.ToInt32((ttl.TotalMilliseconds * ClockDriveFactor) + 2); 119 | var validity_time = ttl - (DateTime.Now - startTime) - new TimeSpan(0, 0, 0, 0, drift); 120 | 121 | if (n >= Quorum && validity_time.TotalMilliseconds > 0) 122 | { 123 | innerLock = new Lock(resource, val, validity_time); 124 | return true; 125 | } 126 | else 127 | { 128 | for_each_redis_registered( 129 | redis => 130 | { 131 | UnlockInstance(redis, resource, val); 132 | } 133 | ); 134 | return false; 135 | } 136 | } 137 | catch (Exception) 138 | { return false; } 139 | }); 140 | 141 | lockObject = innerLock; 142 | return successfull; 143 | } 144 | 145 | protected void for_each_redis_registered(Action action) 146 | { 147 | foreach (var item in redisMasterDictionary) 148 | { 149 | action(item.Value); 150 | } 151 | } 152 | 153 | protected void for_each_redis_registered(Action action) 154 | { 155 | foreach (var item in redisMasterDictionary) 156 | { 157 | action(item.Key); 158 | } 159 | } 160 | 161 | protected bool retry(int retryCount, TimeSpan retryDelay, Func action) 162 | { 163 | int maxRetryDelay = (int)retryDelay.TotalMilliseconds; 164 | Random rnd = new Random(); 165 | int currentRetry = 0; 166 | 167 | while (currentRetry++ < retryCount) 168 | { 169 | if (action()) return true; 170 | Thread.Sleep(rnd.Next(maxRetryDelay)); 171 | } 172 | return false; 173 | } 174 | 175 | public void Unlock(Lock lockObject) 176 | { 177 | for_each_redis_registered(redis => 178 | { 179 | UnlockInstance(redis, lockObject.Resource, lockObject.Value); 180 | }); 181 | } 182 | 183 | public override string ToString() 184 | { 185 | StringBuilder sb = new StringBuilder(); 186 | sb.AppendLine(this.GetType().FullName); 187 | 188 | sb.AppendLine("Registered Connections:"); 189 | foreach(var item in redisMasterDictionary) 190 | { 191 | sb.AppendLine(item.Value.GetEndPoints().First().ToString()); 192 | } 193 | 194 | return sb.ToString(); 195 | } 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /src/redlock-cs/redlock-cs.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | Redlock.CSharp 6 | kidfashion 7 | kidfashion 8 | 2.0.0.0 9 | https://raw.githubusercontent.com/KidFashion/redlock-cs/master/LICENSE 10 | https://github.com/KidFashion/redlock-cs 11 | Distributed lock with Redis and C# (based on http://redis.io/topics/distlock) 12 | 2.0.0.0 13 | redis redlock lock 14 | 2.0.0 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | --------------------------------------------------------------------------------