├── .gitattributes ├── .github └── workflows │ ├── docfx.yml │ ├── pull-request.yml │ └── release.yml ├── .gitignore ├── FreeRedis.sln ├── LICENSE ├── README.md ├── README.zh-CN.md ├── azure-pipelines.yml ├── codecov.yml ├── docfx.json ├── docker-compose.yml ├── env ├── redis.conf └── sentinel.conf ├── examples ├── OpenTelemetryTest │ ├── Controllers │ │ └── WeatherForecastController.cs │ ├── OpenTelemetryTest.csproj │ ├── OpenTelemetryTest.http │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── WeatherForecast.cs │ ├── appsettings.Development.json │ └── appsettings.json ├── console_net452_vs │ ├── App.config │ ├── Program.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ └── console_net452_vs.csproj ├── console_net8 │ ├── Program.cs │ ├── Properties │ │ └── PublishProfiles │ │ │ └── FolderProfile.pubxml │ ├── console_net8.csproj │ └── rd.xml ├── console_net8_benchmark │ ├── Program.cs │ └── console_net8_benchmark.csproj ├── console_net8_client_side_caching │ ├── Program.cs │ └── console_net8_client_side_caching.csproj ├── console_net8_cluster │ ├── Program.cs │ └── console_net8_cluster.csproj ├── console_net8_cluster_client_side_caching │ ├── Program.cs │ └── console_net8_cluster_client_side_caching.csproj ├── console_net8_norman │ ├── Program.cs │ └── console_net8_norman.csproj ├── console_net8_pooling │ ├── Program.cs │ └── console_net8_pooling.csproj ├── console_net8_pubsub │ ├── Program.cs │ └── console_net8_pubsub.csproj ├── console_net8_sentinel │ ├── Program.cs │ └── console_net8_sentinel.csproj └── console_net8_vs │ ├── Program.cs │ └── console_net8_vs.csproj ├── index.md ├── nuget.config ├── scripts ├── build.sh ├── test.sh └── up_converage.sh ├── src ├── FreeRedis.DistributedCache │ ├── .gitattributes │ ├── .gitignore │ ├── FreeRedis.DistributedCache.csproj │ ├── FreeRedisCache.cs │ └── key.snk ├── FreeRedis.OpenTelemetry │ ├── DiagnosticListener.cs │ ├── DiagnosticSourceSubscriber.cs │ ├── FreeRedis.OpenTelemetry.csproj │ ├── FreeRedisInstrumentation.cs │ ├── TracerProviderBuilderExtensions.cs │ └── key.snk └── FreeRedis │ ├── ClientSideCaching.cs │ ├── CommandPacket.cs │ ├── CommandSets.cs │ ├── ConnectionStringBuilder.cs │ ├── FreeRedis.csproj │ ├── FreeRedis.xml │ ├── FreeRedisDiagnosticListenerNames.cs │ ├── IRedisClient.cs │ ├── Internal │ ├── AsyncTestCode │ │ ├── AsyncPipelineRedisSocket.cs │ │ └── AsyncRedisSocket.cs │ ├── DefaultRedisSocket.cs │ ├── IRedisSocket.cs │ ├── IdleBus │ │ ├── IdleBus.cs │ │ ├── IdleBus`1.ItemInfo.cs │ │ ├── IdleBus`1.NoticeEventArgs.cs │ │ ├── IdleBus`1.NoticeType.cs │ │ ├── IdleBus`1.Test.cs │ │ ├── IdleBus`1.ThreadScan.cs │ │ └── IdleBus`1.cs │ ├── ObjectPool │ │ ├── DefaultPolicy.cs │ │ ├── IObjectPool.cs │ │ ├── IPolicy.cs │ │ ├── Object.cs │ │ └── ObjectPool.cs │ ├── RedisClientPool.cs │ ├── RespHelper.cs │ ├── RespHelperAsync.cs │ ├── TempDisposable.cs │ └── _net40.cs │ ├── RedisClient.cs │ ├── RedisClient │ ├── Adapter │ │ ├── BaseAdapter.cs │ │ ├── ClusterAdapter.cs │ │ ├── NormanAdapter.cs │ │ ├── PipelineAdapter.cs │ │ ├── PoolingAdapter.cs │ │ ├── SentinelAdapter.cs │ │ ├── SingleInsideAdapter.cs │ │ ├── SingleTempAdapter.cs │ │ └── TransactionsAdapter.cs │ ├── Cluster.cs │ ├── Connection.cs │ ├── Geo.cs │ ├── Hashes.cs │ ├── HyperLogLog.cs │ ├── Keys.cs │ ├── Lists.cs │ ├── Modules │ │ ├── BloomFilter.cs │ │ ├── CRC16.cs │ │ ├── DelayQueue.cs │ │ ├── Lock.cs │ │ ├── RediSearch.cs │ │ ├── RediSearchBuilder │ │ │ ├── AggregateBuilder.cs │ │ │ ├── CreateBuilder.cs │ │ │ ├── FtDocumentRepository.cs │ │ │ └── SearchBuilder.cs │ │ ├── RedisBloomCountMinSketch.cs │ │ ├── RedisBloomCuckooFilter.cs │ │ ├── RedisBloomTopKFilter.cs │ │ ├── RedisJson.cs │ │ ├── SubscribeList.cs │ │ └── SubscribeStream.cs │ ├── PubSub.cs │ ├── SPubSub.cs │ ├── Scripting.cs │ ├── Server.cs │ ├── Sets.cs │ ├── SortedSets.cs │ ├── Streams.cs │ └── Strings.cs │ ├── RedisClientAsync.cs │ ├── RedisClientEvents.cs │ ├── RedisSentinelClient.cs │ └── key.snk └── test ├── Benchmark └── README.md └── Unit └── FreeRedis.Tests ├── AutoMake.cs ├── CommandFlagsTests.cs ├── CommandPacketTests.cs ├── FreeRedis.Tests.csproj ├── InterceptorTests.cs ├── RedisClientTests ├── AdapterTests │ ├── PipelineTests.cs │ └── TransactionTests.cs ├── ClusterTests.cs ├── ConnectionTests.cs ├── DelayQueueTest.cs ├── GeoTests.cs ├── HashesTests.cs ├── HyperLogLogTests.cs ├── KeysTests.cs ├── ListsTests.cs ├── ModulesTests │ ├── CRC16Tests.cs │ ├── LockTests.cs │ └── RediSearchTests.cs ├── PubSubTests.cs ├── ScriptingTests.cs ├── ServerTests.cs ├── SetsTests.cs ├── SortedSetsTests.cs ├── StreamsTests.cs ├── StringsAsyncTests.cs └── StringsTests.cs ├── RedisEnvironmentHelper.cs ├── RedisScopeExecHelper.cs ├── RedisSentinelClientTests.cs ├── TestBase.cs └── Utils.cs /.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 -------------------------------------------------------------------------------- /.github/workflows/docfx.yml: -------------------------------------------------------------------------------- 1 | name: docfx build 2 | on: 3 | push: 4 | branches: 5 | - master 6 | jobs: 7 | build: 8 | name: Build 9 | runs-on: windows-latest 10 | steps: 11 | # Check out the branch that triggered this workflow to the 'source' subdirectory 12 | - name: Checkout Code 13 | uses: actions/checkout@v2 14 | with: 15 | path: source 16 | - name: install DocFX 17 | run: "& choco install docfx -y" 18 | # Run a build 19 | - name: Build docs 20 | run: "& docfx ./docfx.json" 21 | working-directory: ./source 22 | # Check out gh-pages branch to the 'docs' subdirectory 23 | - name: Checkout docs 24 | uses: actions/checkout@v2 25 | with: 26 | ref: gh-pages 27 | path: docs 28 | # Sync the site 29 | - name: Clear docs repo 30 | run: Get-ChildItem -Force -Exclude .git | ForEach-Object { Remove-Item -Recurse -Verbose -Force $_ } 31 | working-directory: ./docs 32 | - name: Sync new content 33 | run: Copy-Item -Recurse -Verbose -Force "$env:GITHUB_WORKSPACE/source/_site/*" "$env:GITHUB_WORKSPACE/docs" 34 | working-directory: ./docs 35 | # update docs 36 | - name: Commit to gh-pages and push 37 | run: | 38 | $ErrorActionPreference = "Continue" 39 | git add -A 40 | git diff HEAD --exit-code 41 | if ($LASTEXITCODE -eq 0) { 42 | Write-Host "No changes to commit!" 43 | } else { 44 | git config --global user.name "github-actions-docfx[bot]" 45 | git config --global user.email "github-actions-bot@github.com" 46 | git commit -m "Updated docs from commit $env:GITHUB_SHA on $env:GITHUB_REF" 47 | git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }} 48 | git push origin gh-pages 49 | } 50 | working-directory: ./docs -------------------------------------------------------------------------------- /.github/workflows/pull-request.yml: -------------------------------------------------------------------------------- 1 | name: Pull Request Checks 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v1 14 | 15 | - name: Setup .NET Core 3.1 16 | uses: actions/setup-dotnet@v1 17 | with: 18 | dotnet-version: 3.1.300 19 | 20 | - name: Test And Coverage Report 📝 21 | run: | 22 | dotnet build 23 | dotnet test --collect:"XPlat Code Coverage" 24 | find ./test/FreeRedis.tests -name "coverage.cobertura.xml" -type f -exec cp {} ./ \; 25 | bash <(curl -s https://codecov.io/bash) -Z -f coverage.cobertura.xml -t $CODECOV_TOKEN 26 | env: 27 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | env: 4 | NUGET_API_KEY: ${{secrets.NUGET_API_KEY}} 5 | 6 | on: 7 | push: 8 | tags: 9 | - '*' 10 | 11 | jobs: 12 | release-and-publish-package: 13 | runs-on: ubuntu-latest 14 | if: github.repository_owner == '2881099' 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | 19 | - name: Setup .NET Core 20 | uses: actions/setup-dotnet@v1 21 | with: 22 | dotnet-version: 3.1.300 23 | 24 | - name: Package and publish to Nuget📦 25 | run: | 26 | VERSION=`git describe --tags` 27 | echo "Publishing Version: ${VERSION}" 28 | echo "::set-env name=VERSION::${VERSION}" 29 | dotnet build 30 | dotnet pack src/FreeRedis/FreeRedis.csproj /p:PackageVersion=$VERSION -c Release -o publish 31 | dotnet nuget push publish/*.nupkg -s https://api.nuget.org/v3/index.json -k $NUGET_API_KEY --skip-duplicate -------------------------------------------------------------------------------- /.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 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | [Xx]64/ 19 | [Xx]86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | package-lock.json 47 | artifacts/ 48 | 49 | *_i.c 50 | *_p.c 51 | *_i.h 52 | *.ilk 53 | *.meta 54 | *.obj 55 | *.pch 56 | *.pdb 57 | *.pgc 58 | *.pgd 59 | *.rsp 60 | *.sbr 61 | *.tlb 62 | *.tli 63 | *.tlh 64 | *.tmp 65 | *.tmp_proj 66 | *.log 67 | *.vspscc 68 | *.vssscc 69 | .builds 70 | *.pidb 71 | *.svclog 72 | *.scc 73 | 74 | # Chutzpah Test files 75 | _Chutzpah* 76 | 77 | # Visual C++ cache files 78 | ipch/ 79 | *.aps 80 | *.ncb 81 | *.opendb 82 | *.opensdf 83 | *.sdf 84 | *.cachefile 85 | *.VC.db 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | 145 | # TODO: Un-comment the next line if you do not want to checkin 146 | # your web deploy settings because they may include unencrypted 147 | # passwords 148 | #*.pubxml 149 | *.publishproj 150 | 151 | # NuGet Packages 152 | *.nupkg 153 | # The packages folder can be ignored because of Package Restore 154 | **/packages/* 155 | # except build/, which is used as an MSBuild target. 156 | !**/packages/build/ 157 | # Uncomment if necessary however generally it will be regenerated when needed 158 | #!**/packages/repositories.config 159 | # NuGet v3's project.json files produces more ignoreable files 160 | *.nuget.props 161 | *.nuget.targets 162 | 163 | # Microsoft Azure Build Output 164 | csx/ 165 | *.build.csdef 166 | 167 | # Microsoft Azure Emulator 168 | ecf/ 169 | rcf/ 170 | 171 | # Microsoft Azure ApplicationInsights config file 172 | ApplicationInsights.config 173 | 174 | # Windows Store app package directory 175 | AppPackages/ 176 | BundleArtifacts/ 177 | 178 | # Visual Studio cache files 179 | # files ending in .cache can be ignored 180 | *.[Cc]ache 181 | # but keep track of directories ending in .cache 182 | !*.[Cc]ache/ 183 | 184 | # Others 185 | ClientBin/ 186 | [Ss]tyle[Cc]op.* 187 | ~$* 188 | *~ 189 | *.dbmdl 190 | *.dbproj.schemaview 191 | *.publishsettings 192 | node_modules/ 193 | orleans.codegen.cs 194 | 195 | # RIA/Silverlight projects 196 | Generated_Code/ 197 | 198 | # Backup & report files from converting an old project file 199 | # to a newer Visual Studio version. Backup files are not needed, 200 | # because we have git ;-) 201 | _UpgradeReport_Files/ 202 | Backup*/ 203 | UpgradeLog*.XML 204 | UpgradeLog*.htm 205 | 206 | # SQL Server files 207 | *.mdf 208 | *.ldf 209 | 210 | # Business Intelligence projects 211 | *.rdl.data 212 | *.bim.layout 213 | *.bim_*.settings 214 | 215 | # Microsoft Fakes 216 | FakesAssemblies/ 217 | 218 | # GhostDoc plugin setting file 219 | *.GhostDoc.xml 220 | 221 | # Node.js Tools for Visual Studio 222 | .ntvs_analysis.dat 223 | 224 | # Visual Studio 6 build log 225 | *.plg 226 | 227 | # Visual Studio 6 workspace options file 228 | *.opt 229 | 230 | # Visual Studio LightSwitch build output 231 | **/*.HTMLClient/GeneratedArtifacts 232 | **/*.DesktopClient/GeneratedArtifacts 233 | **/*.DesktopClient/ModelManifest.xml 234 | **/*.Server/GeneratedArtifacts 235 | **/*.Server/ModelManifest.xml 236 | _Pvt_Extensions 237 | 238 | # LightSwitch generated files 239 | GeneratedArtifacts/ 240 | ModelManifest.xml 241 | 242 | # Paket dependency manager 243 | .paket/paket.exe 244 | 245 | # FAKE - F# Make 246 | .fake/ 247 | *.rsf 248 | 249 | # JetBrains Rider 250 | .idea/ 251 | *.sln.iml 252 | 253 | # CodeRush 254 | .cr/ 255 | 256 | # Python Tools for Visual Studio (PTVS) 257 | __pycache__/ 258 | *.pyc 259 | 260 | # Cake - Uncomment if you are using it 261 | # tools/** 262 | # !tools/packages.config 263 | 264 | # Tabs Studio 265 | *.tss 266 | 267 | # Telerik's JustMock configuration file 268 | *.jmconfig 269 | 270 | # BizTalk build output 271 | *.btp.cs 272 | *.btm.cs 273 | *.odx.cs 274 | *.xsd.cs 275 | 276 | # OpenCover UI analysis results 277 | OpenCover/ 278 | 279 | # Azure Stream Analytics local run output 280 | ASALocalRun/ 281 | 282 | # MSBuild Binary and Structured Log 283 | *.binlog 284 | 285 | # NVidia Nsight GPU debugger configuration file 286 | *.nvuser 287 | 288 | # MFractors (Xamarin productivity tool) working folder 289 | .mfractor/ 290 | 291 | # docfx 292 | _site 293 | docs/api/*.yml 294 | docs/api/.manifest 295 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 YeXiangQin 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 | -------------------------------------------------------------------------------- /azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | jobs: 2 | - job: build_and_run_ut_by_linux 3 | displayName: Build and Run Unit Test By (Ubuntu:Latest) 4 | timeoutInMinutes: 120 5 | pool: 6 | vmImage: ubuntu-latest 7 | steps: 8 | - task: DockerCompose@0 9 | displayName: "Deploy Docker Compose" 10 | inputs: 11 | action: 'Run a Docker Compose command' 12 | containerregistrytype: 'Container Registry' 13 | dockerComposeFile: '$(Build.SourcesDirectory)/docker-compose.yml' 14 | dockerComposeFileArgs: | 15 | workDirectory=$(Build.SourcesDirectory) 16 | dockerComposeCommand: up -d 17 | - task: UseDotNet@2 18 | displayName: "Install .NET Core SDK" 19 | inputs: 20 | version: 5.0.100 21 | - task: UseDotNet@2 22 | displayName: "Install .NET Core SDK" 23 | inputs: 24 | version: 3.1.403 25 | - script: bash scripts/build.sh 26 | displayName: "Build" 27 | - script: bash scripts/test.sh 28 | displayName: "Run Unit Test" 29 | - task: Palmmedia.reportgenerator.reportgenerator-build-release-task.reportgenerator@4 30 | displayName: ReportGenerator 31 | inputs: 32 | reports: "$(Build.SourcesDirectory)/test/Unit/*/TestResults/*/coverage.cobertura.xml" 33 | targetdir: "$(Build.SourcesDirectory)/CodeCoverage" 34 | reporttypes: "Cobertura" 35 | assemblyfilters: "-xunit*" 36 | - script: bash <(curl -s https://codecov.io/bash) 37 | displayName: "Upload to codecov.io" 38 | - task: DockerCompose@0 39 | displayName : "Down Docker Compose" 40 | inputs: 41 | action: 'Run a Docker Compose command' 42 | containerregistrytype: 'Container Registry' 43 | dockerComposeFile: '$(Build.SourcesDirectory)/docker-compose.yml' 44 | dockerComposeFileArgs: | 45 | workDirectory=$(Build.SourcesDirectory) 46 | dockerComposeCommand: down --remove-orphans 47 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | codecov: 2 | notify: 3 | after_n_builds: 1 -------------------------------------------------------------------------------- /docfx.json: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": [ 3 | { 4 | "src": [ 5 | { 6 | "files": [ 7 | "src/**/*.cs" 8 | ], 9 | "exclude": [ "**/bin/**", "**/obj/**" ] 10 | } 11 | ], 12 | "dest": "docs/api", 13 | "disableGitFeatures": false, 14 | "disableDefaultFilter": false 15 | } 16 | ], 17 | "build": { 18 | "content": [ 19 | { 20 | "files": [ 21 | "docs/ReleaseNotes.md", 22 | "docs/articles/**.md", 23 | "docs/articles/**/toc.yml", 24 | "docs/api/**.md", 25 | "docs/api/**.yml", 26 | "docs/api/**/toc.yml", 27 | "toc.yml", 28 | "*.md" 29 | ] 30 | } 31 | ], 32 | "resource": [ 33 | { 34 | "files": [ 35 | "docs/**/images/**" 36 | ] 37 | } 38 | ], 39 | "overwrite": [ 40 | { 41 | "files": [ 42 | "docs/api/*.md" 43 | ], 44 | "exclude": [ 45 | "obj/**", 46 | "_site/**" 47 | ] 48 | } 49 | ], 50 | "dest": "_site", 51 | "globalMetadataFiles": [], 52 | "fileMetadataFiles": [], 53 | "template": [ 54 | "default" 55 | ], 56 | "postProcessors": [], 57 | "markdownEngineName": "markdig", 58 | "noLangKeyword": false, 59 | "keepFileLink": false, 60 | "cleanupCacheHistory": false, 61 | "disableGitFeatures": false 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.9" 2 | services: 3 | redis_single: 4 | image: redis:6.0-alpine 5 | hostname: "redis_single" 6 | container_name: "redis_single" 7 | volumes: 8 | - ${workDirectory}/env/redis.conf:/usr/local/etc/redis/redis.conf 9 | ports: 10 | - "6379:6379" 11 | command: ["redis-server", "/usr/local/etc/redis/redis.conf"] 12 | redis_interceptor: 13 | image: redis:6.0-alpine 14 | hostname: "redis_interceptor" 15 | container_name: "redis_interceptor" 16 | ports: 17 | - "6479:6379" 18 | command: ["redis-server"] 19 | redis_flush: 20 | image: redis:6.0-alpine 21 | hostname: "redis_flush" 22 | container_name: "redis_flush" 23 | ports: 24 | - "6279:6379" 25 | command: ["redis-server"] 26 | redis_master: 27 | image: redis:6.0-alpine 28 | hostname: "redis_master" 29 | container_name: "redis_master" 30 | ports: 31 | - 6380:6379 32 | redis_sentinel: 33 | image: redis:6.0-alpine 34 | hostname: "redis_sentinel" 35 | container_name: "redis_sentinel" 36 | ports: 37 | - 26379:26379 38 | command: redis-sentinel /usr/local/etc/redis/sentinel.conf 39 | volumes: 40 | - ${workDirectory}/env/sentinel.conf:/usr/local/etc/redis/sentinel.conf -------------------------------------------------------------------------------- /env/redis.conf: -------------------------------------------------------------------------------- 1 | protected-mode no 2 | tcp-backlog 511 3 | timeout 0 4 | tcp-keepalive 300 5 | daemonize no 6 | supervised no 7 | pidfile /var/run/redis_6379.pid 8 | loglevel notice 9 | logfile "" 10 | databases 16 11 | always-show-logo yes 12 | save 900 1 13 | save 300 10 14 | save 60 10000 15 | stop-writes-on-bgsave-error yes 16 | rdbcompression yes 17 | rdbchecksum yes 18 | dbfilename dump.rdb 19 | rdb-del-sync-files no 20 | dir ./ 21 | replica-serve-stale-data yes 22 | replica-read-only yes 23 | repl-diskless-sync no 24 | repl-diskless-sync-delay 5 25 | repl-diskless-load disabled 26 | repl-disable-tcp-nodelay no 27 | replica-priority 100 28 | acllog-max-len 128 29 | requirepass 123456 30 | lazyfree-lazy-eviction no 31 | lazyfree-lazy-expire no 32 | lazyfree-lazy-server-del no 33 | replica-lazy-flush no 34 | lazyfree-lazy-user-del no 35 | oom-score-adj no 36 | oom-score-adj-values 0 200 800 37 | appendonly no 38 | appendfilename "appendonly.aof" 39 | appendfsync everysec 40 | no-appendfsync-on-rewrite no 41 | auto-aof-rewrite-percentage 100 42 | auto-aof-rewrite-min-size 64mb 43 | aof-load-truncated yes 44 | aof-use-rdb-preamble yes 45 | lua-time-limit 5000 46 | slowlog-log-slower-than 10000 47 | slowlog-max-len 128 48 | latency-monitor-threshold 0 49 | notify-keyspace-events "" 50 | hash-max-ziplist-entries 512 51 | hash-max-ziplist-value 64 52 | list-max-ziplist-size -2 53 | list-compress-depth 0 54 | set-max-intset-entries 512 55 | zset-max-ziplist-entries 128 56 | zset-max-ziplist-value 64 57 | hll-sparse-max-bytes 3000 58 | stream-node-max-bytes 4096 59 | stream-node-max-entries 100 60 | activerehashing yes 61 | client-output-buffer-limit normal 0 0 0 62 | client-output-buffer-limit replica 256mb 64mb 60 63 | client-output-buffer-limit pubsub 32mb 8mb 60 64 | hz 10 65 | dynamic-hz yes 66 | aof-rewrite-incremental-fsync yes 67 | rdb-save-incremental-fsync yes 68 | jemalloc-bg-thread yes -------------------------------------------------------------------------------- /env/sentinel.conf: -------------------------------------------------------------------------------- 1 | port 26379 2 | dir /tmp 3 | sentinel monitor mymaster redis_master 6379 2 4 | sentinel auth-pass mymaster redis_pwd 5 | sentinel down-after-milliseconds mymaster 30000 6 | sentinel parallel-syncs mymaster 1 7 | sentinel failover-timeout mymaster 180000 8 | sentinel deny-scripts-reconfig yes -------------------------------------------------------------------------------- /examples/OpenTelemetryTest/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using FreeRedis; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | namespace OpenTelemetryTest.Controllers 5 | { 6 | [ApiController] 7 | [Route("[controller]")] 8 | public class WeatherForecastController : ControllerBase 9 | { 10 | private readonly IRedisClient _redisClient; 11 | private static readonly string[] Summaries = new[] 12 | { 13 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 14 | }; 15 | 16 | private readonly ILogger _logger; 17 | 18 | public WeatherForecastController(ILogger logger, IRedisClient redisClient) 19 | { 20 | _logger = logger; 21 | _redisClient = redisClient; 22 | } 23 | 24 | [HttpGet(Name = "GetWeatherForecast")] 25 | public async Task> Get() 26 | { 27 | var response = Enumerable.Range(1, 20).Select(index => new WeatherForecast 28 | { 29 | Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), 30 | TemperatureC = Random.Shared.Next(-20, 55), 31 | Summary = Summaries[Random.Shared.Next(Summaries.Length)] 32 | }).ToArray(); 33 | 34 | await _redisClient.SetAsync("test01", response, 60 * 5); 35 | await _redisClient.GetAsync("test01"); 36 | 37 | var cache = response.GroupBy(x => x.Summary).ToDictionary(g => g.Key!, g => g.ToList()); 38 | await _redisClient.MSetAsync(cache); 39 | 40 | var cache1 = await _redisClient.GetAsync>(Summaries[Random.Shared.Next(Summaries.Length)]); 41 | 42 | return response; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /examples/OpenTelemetryTest/OpenTelemetryTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /examples/OpenTelemetryTest/OpenTelemetryTest.http: -------------------------------------------------------------------------------- 1 | @OpenTelemetryTest_HostAddress = http://localhost:5252 2 | 3 | GET {{OpenTelemetryTest_HostAddress}}/weatherforecast/ 4 | Accept: application/json 5 | 6 | ### 7 | -------------------------------------------------------------------------------- /examples/OpenTelemetryTest/Program.cs: -------------------------------------------------------------------------------- 1 | using FreeRedis; 2 | using FreeRedis.OpenTelemetry; 3 | using Microsoft.Extensions.DependencyInjection.Extensions; 4 | using OpenTelemetry.Exporter; 5 | using OpenTelemetry.Resources; 6 | using OpenTelemetry.Trace; 7 | 8 | var builder = WebApplication.CreateBuilder(args); 9 | 10 | // Add services to the container. 11 | var services = builder.Services; 12 | builder.Services.AddControllers(); 13 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 14 | builder.Services.AddEndpointsApiExplorer(); 15 | builder.Services.AddSwaggerGen(); 16 | 17 | //redis 18 | var redisClient = new RedisClient(builder.Configuration.GetConnectionString("Redis")); 19 | redisClient.Serialize = obj => System.Text.Json.JsonSerializer.Serialize(obj); 20 | redisClient.Deserialize = (json, type) => System.Text.Json.JsonSerializer.Deserialize(json, type); 21 | //redisClient.Notice += (s, e) => 22 | //{ 23 | // Console.WriteLine(e.Log); 24 | //}; 25 | services.TryAddSingleton(redisClient); 26 | 27 | //OpenTelemetry 28 | var otel = services.AddOpenTelemetry(); 29 | otel.ConfigureResource(resource => 30 | { 31 | resource.AddTelemetrySdk(); 32 | resource.AddEnvironmentVariableDetector(); 33 | resource.AddService("FreeRedisTest"); 34 | }); 35 | var otlpUrl = builder.Configuration["OpenTelemetry:OtlpHttpUrl"]; 36 | otel.WithTracing(tracing => tracing.AddAspNetCoreInstrumentation() 37 | .AddHttpClientInstrumentation() 38 | .AddFreeRedisInstrumentation(redisClient) 39 | .SetSampler(new AlwaysOnSampler()) 40 | //.AddConsoleExporter() 41 | .AddOtlpExporter(otlpOptions => 42 | { 43 | otlpOptions.Endpoint = new Uri($"http://{otlpUrl}/v1/traces"); 44 | otlpOptions.Protocol = OtlpExportProtocol.HttpProtobuf; 45 | otlpOptions.Headers = "Authorization=Basic YWRtaW46dGVzdEAxMjM="; 46 | }) 47 | ); 48 | 49 | var app = builder.Build(); 50 | 51 | // Configure the HTTP request pipeline. 52 | if (app.Environment.IsDevelopment()) 53 | { 54 | app.UseSwagger(); 55 | app.UseSwaggerUI(); 56 | } 57 | 58 | app.UseAuthorization(); 59 | 60 | app.MapControllers(); 61 | 62 | app.Run(); -------------------------------------------------------------------------------- /examples/OpenTelemetryTest/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "profiles": { 4 | "http": { 5 | "commandName": "Project", 6 | "dotnetRunMessages": true, 7 | "launchBrowser": false, 8 | "launchUrl": "weatherforecast", 9 | "applicationUrl": "http://localhost:5000", 10 | "environmentVariables": { 11 | "ASPNETCORE_ENVIRONMENT": "Development" 12 | } 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /examples/OpenTelemetryTest/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | namespace OpenTelemetryTest 2 | { 3 | public class WeatherForecast 4 | { 5 | public DateOnly Date { get; set; } 6 | 7 | public int TemperatureC { get; set; } 8 | 9 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 10 | 11 | public string? Summary { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /examples/OpenTelemetryTest/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "ConnectionStrings": { 9 | "Redis": "127.0.0.1:6379,password=test@123,defaultDatabase=0" 10 | }, 11 | "OpenTelemetry": { 12 | "OtlpHttpUrl": "127.0.0.1:4318" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /examples/OpenTelemetryTest/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /examples/console_net452_vs/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /examples/console_net452_vs/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // 有关程序集的一般信息由以下 6 | // 控制。更改这些特性值可修改 7 | // 与程序集关联的信息。 8 | [assembly: AssemblyTitle("console_net452_vs")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("console_net452_vs")] 13 | [assembly: AssemblyCopyright("Copyright © 2020")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // 将 ComVisible 设置为 false 会使此程序集中的类型 18 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 19 | //请将此类型的 ComVisible 特性设置为 true。 20 | [assembly: ComVisible(false)] 21 | 22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 23 | [assembly: Guid("7ac68251-83d4-423f-849c-04bd89f4bdfb")] 24 | 25 | // 程序集的版本信息由下列四个值组成: 26 | // 27 | // 主版本 28 | // 次版本 29 | // 生成号 30 | // 修订号 31 | // 32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 33 | //通过使用 "*",如下所示: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /examples/console_net452_vs/console_net452_vs.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {7AC68251-83D4-423F-849C-04BD89F4BDFB} 8 | Exe 9 | console_net452_vs 10 | console_net452_vs 11 | v4.5.2 12 | 512 13 | true 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 3.8.800 55 | 56 | 57 | 13.0.1 58 | 59 | 60 | 1.2.6 61 | 62 | 63 | 64 | 65 | {b07c7025-4191-4243-a6ab-34b5be539450} 66 | FreeRedis 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /examples/console_net8/Properties/PublishProfiles/FolderProfile.pubxml: -------------------------------------------------------------------------------- 1 |  2 | 5 | 6 | 7 | Release 8 | Any CPU 9 | bin\Release\net8.0\publish\ 10 | FileSystem 11 | <_TargetId>Folder 12 | 13 | -------------------------------------------------------------------------------- /examples/console_net8/console_net8.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | True 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /examples/console_net8/rd.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /examples/console_net8_benchmark/Program.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using BenchmarkDotNet.Running; 3 | using FreeRedis; 4 | using Newtonsoft.Json; 5 | using System; 6 | using System.Text; 7 | 8 | namespace console_net8_benchmark 9 | { 10 | public class Program 11 | { 12 | static Lazy _cliLazy = new Lazy(() => 13 | { 14 | //var r = new RedisClient("127.0.0.1:6379", false); //redis 3.2 Single test 15 | var r = new RedisClient("127.0.0.1:6379,database=1,poolsize=100,min pool size=100"); //redis 3.2 16 | //var r = new RedisClient("127.0.0.1:6379,database=1", "127.0.0.1:6379,database=1"); 17 | //var r = new RedisClient("192.168.164.10:6379,database=1"); //redis 6.0 18 | r.Serialize = obj => JsonConvert.SerializeObject(obj); 19 | r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type); 20 | //r.Notice += (s, e) => Trace.WriteLine(e.Log); 21 | return r; 22 | }); 23 | static RedisClient cli => _cliLazy.Value; 24 | static CSRedis.CSRedisClient csredis = new CSRedis.CSRedisClient("127.0.0.1:6379,database=2,poolsize=100"); 25 | static StackExchange.Redis.ConnectionMultiplexer seredis = StackExchange.Redis.ConnectionMultiplexer.Connect("127.0.0.1:6379"); 26 | static StackExchange.Redis.IDatabase sedb = seredis.GetDatabase(1); 27 | 28 | public static void Main(string[] args) 29 | { 30 | RedisHelper.Initialization(csredis); 31 | cli.Set("TestMGet_string1", String); 32 | RedisHelper.Set("TestMGet_string1", String); 33 | sedb.StringSet("TestMGet_string1", String); 34 | 35 | var summary = BenchmarkRunner.Run(); 36 | } 37 | 38 | public class SetVs 39 | { 40 | [Benchmark] 41 | public void FreeRedis() 42 | { 43 | //cli.Set("TestMGet_string1", String); 44 | cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String)); 45 | } 46 | 47 | [Benchmark] 48 | public void CSRedisCore() 49 | { 50 | csredis.Set("TestMGet_string1", String); 51 | } 52 | 53 | [Benchmark] 54 | public void StackExchange() 55 | { 56 | sedb.StringSet("TestMGet_string1", String); 57 | } 58 | } 59 | 60 | static readonly string String = "我是中国人"; 61 | } 62 | 63 | public class TestClass 64 | { 65 | public int Id { get; set; } 66 | public string Name { get; set; } 67 | public DateTime CreateTime { get; set; } 68 | 69 | public int[] TagId { get; set; } 70 | 71 | public override string ToString() 72 | { 73 | return JsonConvert.SerializeObject(this); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /examples/console_net8_benchmark/console_net8_benchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /examples/console_net8_client_side_caching/Program.cs: -------------------------------------------------------------------------------- 1 | using FreeRedis; 2 | using Newtonsoft.Json; 3 | using System; 4 | using System.Globalization; 5 | using System.Threading; 6 | 7 | namespace console_net8_client_side_caching 8 | { 9 | class Program 10 | { 11 | static Lazy _cliLazy = new Lazy(() => 12 | { 13 | var r = new RedisClient("127.0.0.1:6379"); //redis 3.2 Single test 14 | //var r = new RedisClient("192.168.164.10:6379"); //redis 3.2 Single test 15 | //var r = new RedisClient("127.0.0.1:6379,database=1,min pool size=500,max pool size=500"); //redis 3.2 16 | //var r = new RedisClient("127.0.0.1:6379,database=10", "127.0.0.1:6380,database=10", "127.0.0.1:6381,database=10"); 17 | //var r = new RedisClient(new [] { (ConnectionStringBuilder)"192.168.164.10:6379,database=1", (ConnectionStringBuilder)"192.168.164.10:6379,database=2" }); //redis 6.0 18 | r.Serialize = obj => JsonConvert.SerializeObject(obj); 19 | r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type); 20 | r.Notice += (s, e) => Console.WriteLine(e.Log); 21 | return r; 22 | // redis6 cluster 23 | // https://www.cnblogs.com/sharktech/p/14475748.html 24 | // /redis6-cluster.sh 25 | // ps -ef | grep redis 26 | // redis-cli --cluster create 0.0.0.0:6379 0.0.0.0:6380 0.0.0.0:6381 0.0.0.0:6382 0.0.0.0:6383 0.0.0.0:6384 --cluster-replicas 1 -a 123456 27 | }); 28 | static RedisClient cli => _cliLazy.Value; 29 | 30 | static void Main(string[] args) 31 | { 32 | Thread.CurrentThread.CurrentCulture = new CultureInfo("nb"); 33 | var test = long.Parse("-1"); 34 | 35 | cli.Notice += (s, e) => 36 | { 37 | if (e.NoticeType == NoticeType.Event && e.Log == "ClientSideCaching:InValidate") 38 | { 39 | var keys = e.Tag as string[]; 40 | } 41 | }; 42 | cli.UseClientSideCaching(new ClientSideCachingOptions 43 | { 44 | //本地缓存的容量 45 | Capacity = 3, 46 | //过滤哪些键能被本地缓存 47 | //KeyFilter = key => key.StartsWith("Interceptor"), 48 | //检查长期未使用的缓存 49 | CheckExpired = (key, dt) => DateTime.Now.Subtract(dt) > TimeSpan.FromSeconds(600) 50 | }); 51 | 52 | while (Console.ReadKey().Key != ConsoleKey.Escape) 53 | { 54 | Console.WriteLine(cli.HGetAll("hash01")); 55 | Console.WriteLine(cli.HGet("hash01", "f3")); 56 | Console.WriteLine(cli.HMGet("hash01", "f3", "f2")); 57 | } 58 | 59 | cli.Set("Interceptor01", "123123"); //redis-server 60 | 61 | var val1 = cli.Get("Interceptor01"); //redis-server 62 | var val2 = cli.Get("Interceptor01"); //本地 63 | var val3 = cli.Get("Interceptor01"); //断点等3秒,redis-server 64 | 65 | cli.Set("Interceptor01", "234567"); //redis-server 66 | var val4 = cli.Get("Interceptor01"); //redis-server 67 | var val5 = cli.Get("Interceptor01"); //本地 68 | 69 | var val6 = cli.MGet("Interceptor01", "Interceptor02", "Interceptor03"); //redis-server 70 | var val7 = cli.MGet("Interceptor01", "Interceptor02", "Interceptor03"); //本地 71 | var val8 = cli.MGet("Interceptor01", "Interceptor02", "Interceptor03"); //本地 72 | 73 | cli.MSet("Interceptor01", "Interceptor01Value", "Interceptor02", "Interceptor02Value", "Interceptor03", "Interceptor03Value"); //redis-server 74 | var val9 = cli.MGet("Interceptor01", "Interceptor02", "Interceptor03"); //redis-server 75 | var val10 = cli.MGet("Interceptor01", "Interceptor02", "Interceptor03"); //本地 76 | 77 | //以下 KeyFilter 返回 false,从而不使用本地缓存 78 | cli.Set("123Interceptor01", "123123"); //redis-server 79 | 80 | var val11 = cli.Get("123Interceptor01"); //redis-server 81 | var val12 = cli.Get("123Interceptor01"); //redis-server 82 | var val23 = cli.Get("123Interceptor01"); //redis-server 83 | 84 | 85 | cli.Set("Interceptor011", Class); //redis-server 86 | var val0111 = cli.Get("Interceptor011"); //redis-server 87 | var val0112 = cli.Get("Interceptor011"); //本地 88 | var val0113 = cli.Get("Interceptor011"); //断点等3秒,redis-server 89 | 90 | Console.WriteLine("all test has done running"); 91 | Console.ReadKey(); 92 | 93 | cli.Dispose(); 94 | } 95 | 96 | static readonly TestClass Class = new TestClass { Id = 1, Name = "Class名称", CreateTime = DateTime.Now, TagId = new[] { 1, 3, 3, 3, 3 } }; 97 | } 98 | 99 | public class TestClass 100 | { 101 | public int Id { get; set; } 102 | public string Name { get; set; } 103 | public DateTime CreateTime { get; set; } 104 | 105 | public int[] TagId { get; set; } 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /examples/console_net8_client_side_caching/console_net8_client_side_caching.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /examples/console_net8_cluster/Program.cs: -------------------------------------------------------------------------------- 1 | using FreeRedis; 2 | using Newtonsoft.Json; 3 | using StackExchange.Redis; 4 | using System; 5 | using System.Diagnostics; 6 | 7 | namespace console_net8_cluster 8 | { 9 | class Program 10 | { 11 | static Lazy _cliLazy = new Lazy(() => 12 | { 13 | var r = new RedisClient(new ConnectionStringBuilder[] { "127.0.0.1:6379", "127.0.0.1:6380" }); 14 | r.Serialize = obj => JsonConvert.SerializeObject(obj); 15 | r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type); 16 | //r.Notice += (s, e) => Trace.WriteLine(e.Log); 17 | return r; 18 | }); 19 | 20 | static RedisClient cli => _cliLazy.Value; 21 | 22 | static CSRedis.CSRedisClient csredis = new CSRedis.CSRedisClient("127.0.0.1:6379"); 23 | 24 | static ConnectionMultiplexer seredis = ConnectionMultiplexer.Connect("127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381"); 25 | static IDatabase sedb => seredis.GetDatabase(); 26 | 27 | static void Main(string[] args) 28 | { 29 | var tblv1 = cli.BLPop("testblist01", 5); 30 | var tblv2 = cli.BLPop("testblist02", 5); 31 | var tblv3 = cli.BLPop("testblist03", 5); 32 | 33 | cli.LPush("testblist01", "value1"); 34 | tblv1 = cli.BLPop("testblist01", 5); 35 | cli.LPush("testblist02", "value2"); 36 | tblv2 = cli.BLPop("testblist02", 5); 37 | cli.LPush("testblist03", "value3"); 38 | tblv3 = cli.BLPop("testblist03", 5); 39 | 40 | //预热 41 | cli.Set(Guid.NewGuid().ToString(), "我也不知道为什么刚刚好十五个字"); 42 | sedb.StringSet(Guid.NewGuid().ToString(), "我也不知道为什么刚刚好十五个字"); 43 | 44 | Stopwatch stopwatch = new Stopwatch(); 45 | stopwatch.Start(); 46 | 47 | for (int i = 0; i < 10000; i++) 48 | { 49 | var tmp = Guid.NewGuid().ToString(); 50 | cli.Set(tmp, "我也不知道为什么刚刚好十五个字"); 51 | var val = cli.Get(tmp); 52 | if (val != "我也不知道为什么刚刚好十五个字") throw new Exception("not equal"); 53 | } 54 | 55 | stopwatch.Stop(); 56 | Console.WriteLine("FreeRedis:"+stopwatch.ElapsedMilliseconds); 57 | 58 | //stopwatch.Restart(); 59 | // csredis 会出现连接不能打开的情况 60 | //for (int i = 0; i < 100; i++) 61 | //{ 62 | // var tmp = Guid.NewGuid().ToString(); 63 | // csredis.Set(tmp, "我也不知道为什么刚刚好十五个字"); 64 | // _ = csredis.Get(tmp); 65 | //} 66 | 67 | //stopwatch.Stop(); 68 | //Console.WriteLine("csredis:" + stopwatch.ElapsedMilliseconds); 69 | 70 | stopwatch.Restart(); 71 | 72 | for (int i = 0; i < 10000; i++) 73 | { 74 | var tmp = Guid.NewGuid().ToString(); 75 | sedb.StringSet(tmp, "我也不知道为什么刚刚好十五个字"); 76 | var val = sedb.StringGet(tmp); 77 | if (val != "我也不知道为什么刚刚好十五个字") throw new Exception("not equal"); 78 | } 79 | 80 | stopwatch.Stop(); 81 | Console.WriteLine("Seredis:" + stopwatch.ElapsedMilliseconds); 82 | 83 | cli.Subscribe("abc", (chan, msg) => 84 | { 85 | Console.WriteLine($"FreeRedis {chan} => {msg}"); 86 | }); 87 | 88 | seredis.GetSubscriber().Subscribe("abc", (chan, msg) => 89 | { 90 | Console.WriteLine($"Seredis {chan} => {msg}"); 91 | }); 92 | Console.ReadKey(); 93 | 94 | return; 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /examples/console_net8_cluster/console_net8_cluster.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /examples/console_net8_cluster_client_side_caching/Program.cs: -------------------------------------------------------------------------------- 1 | using FreeRedis; 2 | using System.Diagnostics; 3 | 4 | class Program 5 | { 6 | static RedisClient CreateRedisClient() 7 | { 8 | var cli = new RedisClient(new[] { (ConnectionStringBuilder)"192.168.164.10:6380,password=123456,min pool size=10" }); 9 | cli.UseClientSideCaching(new ClientSideCachingOptions 10 | { 11 | //本地缓存的容量 12 | Capacity = 99999, 13 | //过滤哪些键能被本地缓存 14 | KeyFilter = key => true, 15 | //检查长期未使用的缓存 16 | CheckExpired = (key, dt) => DateTime.Now.Subtract(dt) > TimeSpan.FromSeconds(600) 17 | }); 18 | return cli; 19 | // redis6 cluster 20 | // https://www.cnblogs.com/sharktech/p/14475748.html 21 | // /redis6-cluster.sh 22 | // ps -ef | grep redis 23 | // redis-cli --cluster create 0.0.0.0:6379 0.0.0.0:6380 0.0.0.0:6381 0.0.0.0:6382 0.0.0.0:6383 0.0.0.0:6384 --cluster-replicas 1 -a 123456 24 | } 25 | 26 | 27 | static void Main(string[] args) 28 | { 29 | 30 | var testCount = 10; 31 | Console.WriteLine($"测试 {testCount} 个 RedisClient Cluster 客户端缓存功能 client side cahcing"); 32 | Console.WriteLine($"正在创建 {testCount} 个 RedisCient 对象...\r\n"); 33 | var clis = new List(); 34 | for(var a = 0; a < testCount; a++) 35 | { 36 | clis.Add(CreateRedisClient()); 37 | } 38 | 39 | var key = Guid.NewGuid().ToString(); 40 | string value = null; 41 | 42 | Console.WriteLine($"{clis.Count} 个 RedisClient 对象创建完成.\r\n"); 43 | Console.WriteLine($"【Esc】退出程序"); 44 | Console.WriteLine($"【Enter】对比 {clis.Count} 值同步"); 45 | Console.WriteLine($"【1】刷新新值\r\n"); 46 | 47 | Console.WriteLine($"本次测试 key: {key}\r\n\r\n"); 48 | 49 | while (true) 50 | { 51 | var readkey = Console.ReadKey().Key; 52 | if (readkey == ConsoleKey.Escape) break; 53 | 54 | if (readkey == ConsoleKey.Enter) 55 | { 56 | var sw = new Stopwatch(); 57 | sw.Reset(); 58 | sw.Start(); 59 | var equalsCounter = 0; 60 | foreach (var cli in clis) 61 | { 62 | if (value == cli.Get(key)) equalsCounter++; 63 | } 64 | sw.Stop(); 65 | Console.WriteLine($"RedisClient[0..{clis.Count}] Get 新值比较,耗时 {sw.ElapsedMilliseconds}ms,相同 {equalsCounter},不相同 {(clis.Count - equalsCounter)}"); 66 | } 67 | 68 | if (readkey == ConsoleKey.D1) 69 | { 70 | value = Guid.NewGuid().ToString(); 71 | clis[0].Set(key, value); 72 | Console.WriteLine($"RedisClient[0] Set 新值已写入 {value}"); 73 | } 74 | } 75 | 76 | Console.WriteLine($"正在退出..."); 77 | foreach (var cli in clis) cli.Dispose(); 78 | Console.WriteLine($"退出成功."); 79 | } 80 | } -------------------------------------------------------------------------------- /examples/console_net8_cluster_client_side_caching/console_net8_cluster_client_side_caching.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /examples/console_net8_norman/Program.cs: -------------------------------------------------------------------------------- 1 | using FreeRedis; 2 | using Newtonsoft.Json; 3 | using System; 4 | using System.Diagnostics; 5 | 6 | namespace console_net8_norman 7 | { 8 | class Program 9 | { 10 | static Lazy _cliLazy = new Lazy(() => 11 | { 12 | var r = new RedisClient(new ConnectionStringBuilder[] { "127.0.0.1:6379,database=1", "127.0.0.1:6379,database=2" }, default(Func)); 13 | r.Serialize = obj => JsonConvert.SerializeObject(obj); 14 | r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type); 15 | r.Notice += (s, e) => Console.WriteLine(e.Log); 16 | return r; 17 | }); 18 | static RedisClient cli => _cliLazy.Value; 19 | 20 | static void Main(string[] args) 21 | { 22 | //预热 23 | cli.Set(Guid.NewGuid().ToString(), "我也不知道为什么刚刚好十五个字"); 24 | 25 | Stopwatch stopwatch = new Stopwatch(); 26 | stopwatch.Start(); 27 | 28 | for (int i = 0; i < 10000; i++) 29 | { 30 | var tmp = Guid.NewGuid().ToString(); 31 | cli.Set(tmp, "我也不知道为什么刚刚好十五个字"); 32 | var val = cli.Get(tmp); 33 | if (val != "我也不知道为什么刚刚好十五个字") throw new Exception("not equal"); 34 | } 35 | 36 | stopwatch.Stop(); 37 | Console.WriteLine("FreeRedis:" + stopwatch.ElapsedMilliseconds); 38 | } 39 | 40 | static readonly string String = "我是中国人"; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /examples/console_net8_norman/console_net8_norman.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /examples/console_net8_pooling/Program.cs: -------------------------------------------------------------------------------- 1 | using FreeRedis; 2 | using System; 3 | using System.Threading; 4 | 5 | namespace console_net8_pooling 6 | { 7 | class Program 8 | { 9 | static Lazy _cliLazy = new Lazy(() => 10 | { 11 | //var r = new RedisClient("127.0.0.1:6379", false); //redis 3.2 Single test 12 | var r = new RedisClient("127.0.0.1:6379,database=10"); //redis 3.2 13 | //var r = new RedisClient("127.0.0.1:6379,database=1", "127.0.0.1:6379,database=1"); 14 | //var r = new RedisClient("192.168.164.10:6379,database=1"); //redis 6.0 15 | //r.Serialize = obj => JsonConvert.SerializeObject(obj); 16 | //r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type); 17 | //r.Notice += (s, e) => Trace.WriteLine(e.Log); 18 | return r; 19 | }); 20 | static RedisClient cli => _cliLazy.Value; 21 | 22 | static void Main(string[] args) 23 | { 24 | //网络出错后,断熔,后台线程定时检查恢复 25 | for (var k = 0; k < 1; k++) 26 | { 27 | new Thread(() => 28 | { 29 | for (var a = 0; a < 10000; a++) 30 | { 31 | try 32 | { 33 | cli.Get(Guid.NewGuid().ToString()); 34 | } 35 | catch (Exception ex) 36 | { 37 | Console.WriteLine(ex.Message); 38 | } 39 | Thread.CurrentThread.Join(100); 40 | } 41 | }).Start(); 42 | } 43 | 44 | Console.ReadKey(); 45 | return; 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /examples/console_net8_pooling/console_net8_pooling.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /examples/console_net8_pubsub/Program.cs: -------------------------------------------------------------------------------- 1 | using FreeRedis; 2 | using System; 3 | 4 | namespace console_net8 5 | { 6 | class Program 7 | { 8 | static Lazy _cliLazy = new Lazy(() => 9 | { 10 | //var r = new RedisClient("127.0.0.1:6379", false); //redis 3.2 Single test 11 | var r = new RedisClient("127.0.0.1:6379,database=10"); //redis 3.2 12 | //var r = new RedisClient("127.0.0.1:6379,database=1", "127.0.0.1:6379,database=1"); 13 | //var r = new RedisClient("192.168.164.10:6379,database=1"); //redis 6.0 14 | //r.Serialize = obj => JsonConvert.SerializeObject(obj); 15 | //r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type); 16 | //r.Notice += (s, e) => Trace.WriteLine(e.Log); 17 | return r; 18 | }); 19 | static RedisClient cli => _cliLazy.Value; 20 | 21 | static void Main(string[] args) 22 | { 23 | using (var local = cli.GetDatabase()) 24 | { 25 | var r1 = local.Call(new CommandPacket("Subscribe").Input("abc")); 26 | var r2 = local.Ping(); 27 | var r3 = local.Ping("testping123"); 28 | //var r4 = local.Call(new CommandPacket("punSubscribe").Input("*")); 29 | } 30 | 31 | using (cli.Subscribe("abc", ondata)) 32 | { 33 | using (cli.Subscribe("abcc", ondata)) 34 | { 35 | using (cli.PSubscribe("*", ondata)) 36 | { 37 | Console.ReadKey(); 38 | } 39 | Console.ReadKey(); 40 | } 41 | Console.ReadKey(); 42 | } 43 | Console.WriteLine("one more time"); 44 | Console.ReadKey(); 45 | using (cli.Subscribe("abc", ondata)) 46 | { 47 | using (cli.Subscribe("abcc", ondata)) 48 | { 49 | using (cli.PSubscribe("*", ondata)) 50 | { 51 | Console.ReadKey(); 52 | } 53 | Console.ReadKey(); 54 | } 55 | Console.ReadKey(); 56 | } 57 | void ondata(string channel, object data) 58 | { 59 | Console.WriteLine($"{channel} -> {data}"); 60 | } 61 | //return; 62 | } 63 | 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /examples/console_net8_pubsub/console_net8_pubsub.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /examples/console_net8_sentinel/Program.cs: -------------------------------------------------------------------------------- 1 | using FreeRedis; 2 | using Newtonsoft.Json; 3 | using System; 4 | using System.Threading; 5 | 6 | namespace console_net8_sentinel 7 | { 8 | class Program 9 | { 10 | static Lazy _cliLazy = new Lazy(() => 11 | { 12 | var r = new RedisClient("mymaster,database=3", new[] { "127.0.0.1:26379", "127.0.0.1:26479", "127.0.0.1:26579" }, true); 13 | r.Serialize = obj => JsonConvert.SerializeObject(obj); 14 | r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type); 15 | r.Notice += (s, e) => Console.WriteLine(e.Log); 16 | return r; 17 | }); 18 | static RedisClient cli => _cliLazy.Value; 19 | 20 | static void Main(string[] args) 21 | { 22 | while (Console.ReadKey().Key == ConsoleKey.Enter) 23 | { 24 | try 25 | { 26 | cli.Get(Guid.NewGuid().ToString()); 27 | cli.Set(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); 28 | } 29 | catch (Exception ex) 30 | { 31 | Console.WriteLine(ex.Message); 32 | } 33 | } 34 | 35 | return; 36 | 37 | for (var k = 0; k < 1; k++) 38 | { 39 | new Thread(() => 40 | { 41 | for (var a = 0; a < 10000; a++) 42 | { 43 | try 44 | { 45 | cli.Get(Guid.NewGuid().ToString()); 46 | } 47 | catch (Exception ex) 48 | { 49 | Console.WriteLine(ex.Message); 50 | } 51 | Thread.CurrentThread.Join(100); 52 | } 53 | }).Start(); 54 | } 55 | 56 | Console.ReadKey(); 57 | return; 58 | } 59 | 60 | } 61 | 62 | public class TestClass 63 | { 64 | public int Id { get; set; } 65 | public string Name { get; set; } 66 | public DateTime CreateTime { get; set; } 67 | 68 | public int[] TagId { get; set; } 69 | 70 | public override string ToString() 71 | { 72 | return JsonConvert.SerializeObject(this); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /examples/console_net8_sentinel/console_net8_sentinel.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /examples/console_net8_vs/console_net8_vs.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /nuget.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /scripts/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | dotnet sln remove examples/* 3 | dotnet restore -v quiet "FreeRedis.sln" 4 | dotnet build /clp:ErrorsOnly -v quiet "FreeRedis.sln" -------------------------------------------------------------------------------- /scripts/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | while read name _ _ _ _ ports; do 4 | key="DOCKER_HOST_$name" 5 | # 0.0.0.0:1234->9876/tcp,first 6 | tempPort=$(cut -d'-' -f1 <<<"$ports") 7 | vr="$key=$tempPort" 8 | echo "$vr" 9 | export "$vr" 10 | done <<<$(docker-compose -p tomatopunk/FreeRedis ps --filter "State="up"" | awk 'FNR > 2') 11 | 12 | #echo $(printenv DOCKER_HOST_redis_auth) 13 | #echo $(printenv DOCKER_HOST_redis_single) 14 | 15 | echo "setup is finished" 16 | 17 | cd test/Unit/ || exit 18 | 19 | for i in *.Tests; do 20 | echo "### Executing Tests for $i:" 21 | 22 | time dotnet test "$i" --no-build \ 23 | --collect:"XPlat Code Coverage" \ 24 | -- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.ExcludeByFile="examples/*" \ 25 | >/tmp/freeredis-test.log 26 | 27 | if [[ $? -ne 0 ]]; then 28 | echo "Test Run Failed." 29 | cat /tmp/freeredis-test.log 30 | exit 1 31 | fi 32 | echo "Test Run Successful." 33 | done 34 | -------------------------------------------------------------------------------- /scripts/up_converage.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | curl -s https://codecov.io/bash > codecov 4 | chmod +x codecov 5 | ./codecov -f "$(Build.SourcesDirectory)/CodeCoverage/Cobertura.xml" -t $1 -------------------------------------------------------------------------------- /src/FreeRedis.DistributedCache/.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 | -------------------------------------------------------------------------------- /src/FreeRedis.DistributedCache/.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 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | [Xx]64/ 19 | [Xx]86/ 20 | [Bb]uild/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | package-lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | 86 | # Visual Studio profiler 87 | *.psess 88 | *.vsp 89 | *.vspx 90 | *.sap 91 | 92 | # TFS 2012 Local Workspace 93 | $tf/ 94 | 95 | # Guidance Automation Toolkit 96 | *.gpState 97 | 98 | # ReSharper is a .NET coding add-in 99 | _ReSharper*/ 100 | *.[Rr]e[Ss]harper 101 | *.DotSettings.user 102 | 103 | # JustCode is a .NET coding add-in 104 | .JustCode 105 | 106 | # TeamCity is a build add-in 107 | _TeamCity* 108 | 109 | # DotCover is a Code Coverage Tool 110 | *.dotCover 111 | 112 | # NCrunch 113 | _NCrunch_* 114 | .*crunch*.local.xml 115 | nCrunchTemp_* 116 | 117 | # MightyMoose 118 | *.mm.* 119 | AutoTest.Net/ 120 | 121 | # Web workbench (sass) 122 | .sass-cache/ 123 | 124 | # Installshield output folder 125 | [Ee]xpress/ 126 | 127 | # DocProject is a documentation generator add-in 128 | DocProject/buildhelp/ 129 | DocProject/Help/*.HxT 130 | DocProject/Help/*.HxC 131 | DocProject/Help/*.hhc 132 | DocProject/Help/*.hhk 133 | DocProject/Help/*.hhp 134 | DocProject/Help/Html2 135 | DocProject/Help/html 136 | 137 | # Click-Once directory 138 | publish/ 139 | 140 | # Publish Web Output 141 | *.[Pp]ublish.xml 142 | *.azurePubxml 143 | 144 | # TODO: Un-comment the next line if you do not want to checkin 145 | # your web deploy settings because they may include unencrypted 146 | # passwords 147 | #*.pubxml 148 | *.publishproj 149 | 150 | # NuGet Packages 151 | *.nupkg 152 | # The packages folder can be ignored because of Package Restore 153 | **/packages/* 154 | # except build/, which is used as an MSBuild target. 155 | !**/packages/build/ 156 | # Uncomment if necessary however generally it will be regenerated when needed 157 | #!**/packages/repositories.config 158 | # NuGet v3's project.json files produces more ignoreable files 159 | *.nuget.props 160 | *.nuget.targets 161 | 162 | # Microsoft Azure Build Output 163 | csx/ 164 | *.build.csdef 165 | 166 | # Microsoft Azure Emulator 167 | ecf/ 168 | rcf/ 169 | 170 | # Microsoft Azure ApplicationInsights config file 171 | ApplicationInsights.config 172 | 173 | # Windows Store app package directory 174 | AppPackages/ 175 | BundleArtifacts/ 176 | 177 | # Visual Studio cache files 178 | # files ending in .cache can be ignored 179 | *.[Cc]ache 180 | # but keep track of directories ending in .cache 181 | !*.[Cc]ache/ 182 | 183 | # Others 184 | ClientBin/ 185 | [Ss]tyle[Cc]op.* 186 | ~$* 187 | *~ 188 | *.dbmdl 189 | *.dbproj.schemaview 190 | *.publishsettings 191 | node_modules/ 192 | orleans.codegen.cs 193 | 194 | # RIA/Silverlight projects 195 | Generated_Code/ 196 | 197 | # Backup & report files from converting an old project file 198 | # to a newer Visual Studio version. Backup files are not needed, 199 | # because we have git ;-) 200 | _UpgradeReport_Files/ 201 | Backup*/ 202 | UpgradeLog*.XML 203 | UpgradeLog*.htm 204 | 205 | # SQL Server files 206 | *.mdf 207 | *.ldf 208 | 209 | # Business Intelligence projects 210 | *.rdl.data 211 | *.bim.layout 212 | *.bim_*.settings 213 | 214 | # Microsoft Fakes 215 | FakesAssemblies/ 216 | 217 | # GhostDoc plugin setting file 218 | *.GhostDoc.xml 219 | 220 | # Node.js Tools for Visual Studio 221 | .ntvs_analysis.dat 222 | 223 | # Visual Studio 6 build log 224 | *.plg 225 | 226 | # Visual Studio 6 workspace options file 227 | *.opt 228 | 229 | # Visual Studio LightSwitch build output 230 | **/*.HTMLClient/GeneratedArtifacts 231 | **/*.DesktopClient/GeneratedArtifacts 232 | **/*.DesktopClient/ModelManifest.xml 233 | **/*.Server/GeneratedArtifacts 234 | **/*.Server/ModelManifest.xml 235 | _Pvt_Extensions 236 | 237 | # LightSwitch generated files 238 | GeneratedArtifacts/ 239 | ModelManifest.xml 240 | 241 | # Paket dependency manager 242 | .paket/paket.exe 243 | 244 | # FAKE - F# Make 245 | .fake/ -------------------------------------------------------------------------------- /src/FreeRedis.DistributedCache/FreeRedis.DistributedCache.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | netstandard2.0;net80;net70;net60;net50;netcoreapp31 4 | FreeRedis.DistributedCache 5 | FreeRedis.DistributedCache 6 | FreeRedis.DistributedCache 7 | 1.3.8 8 | true 9 | https://github.com/2881099/FreeRedis 10 | 分布式缓存 FreeRedis 实现 Microsoft.Extensions.Caching 11 | https://github.com/2881099/FreeRedis 12 | caching freeredis redis c# 分布式缓存 集群 负载 cluster Microsoft.Extensions.Caching 13 | true 14 | key.snk 15 | false 16 | readme.md 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | bin\Debug\netstandard2.0\Caching.CSRedis.xml 25 | 3 26 | 1701;1702;1591 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /src/FreeRedis.DistributedCache/key.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2881099/FreeRedis/cc5bdb638a1035cc64b9bdc2778a2875cf46b1d9/src/FreeRedis.DistributedCache/key.snk -------------------------------------------------------------------------------- /src/FreeRedis.OpenTelemetry/DiagnosticListener.cs: -------------------------------------------------------------------------------- 1 | using OpenTelemetry.Trace; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | 6 | namespace FreeRedis.OpenTelemetry 7 | { 8 | 9 | public class DiagnosticListener : IObserver> 10 | { 11 | public const string SourceName = "FreeRedis.OpenTelemetry"; 12 | 13 | private static readonly ActivitySource ActivitySource = new(SourceName, "1.0.0"); 14 | 15 | /// Notifies the observer that the provider has finished sending push-based notifications. 16 | public void OnCompleted() 17 | { 18 | } 19 | 20 | /// Notifies the observer that the provider has experienced an error condition. 21 | /// An object that provides additional information about the error. 22 | public void OnError(Exception error) 23 | { 24 | } 25 | 26 | /// Provides the observer with new data. 27 | /// The current notification information. 28 | public void OnNext(KeyValuePair evt) 29 | { 30 | //https://opentelemetry.io/docs/specs/semconv/database/redis/ 31 | switch (evt.Key) 32 | { 33 | case FreeRedisDiagnosticListenerNames.NoticeCallBefore: 34 | { 35 | var eventData = (InterceptorBeforeEventArgs)evt.Value!; 36 | var activity = ActivitySource.StartActivity("redis command execute: " + eventData.Command); 37 | if (activity != null) 38 | { 39 | activity.SetTag("db.system", "redis"); 40 | activity.SetTag("db.operation.name", eventData.Command._command); 41 | activity.SetTag("db.query.text", eventData.Command); 42 | //Activity.Current?.SetTag("network.peer.address", ip); 43 | //Activity.Current?.SetTag("network.peer.port", port); 44 | 45 | activity.AddEvent(new ActivityEvent("redis command execute start", 46 | DateTimeOffset.FromUnixTimeMilliseconds(eventData.OperationTimestamp!.Value))); 47 | } 48 | } 49 | break; 50 | case FreeRedisDiagnosticListenerNames.NoticeCallAfter: 51 | { 52 | var eventData = (InterceptorAfterEventArgs)evt.Value!; 53 | var writeTarget = eventData.Command.WriteTarget; 54 | if (!string.IsNullOrEmpty(writeTarget)) 55 | { 56 | var parts = writeTarget.Split(new[] { ':', '/' }, StringSplitOptions.RemoveEmptyEntries); 57 | var ip = parts[0]; 58 | var port = int.Parse(parts[1]); 59 | var dbIndex = int.Parse(parts[2]); 60 | 61 | Activity.Current?.SetTag("server.address", ip); 62 | Activity.Current?.SetTag("server.port", port); 63 | Activity.Current?.SetTag("db.namespace", dbIndex); 64 | } 65 | var tags = new ActivityTagsCollection { new("free_redis.duration", eventData.ElapsedMilliseconds) }; 66 | if (eventData.Exception != null) 67 | { 68 | Activity.Current?.SetStatus(Status.Error.WithDescription(eventData.Exception.Message)); 69 | tags.Add(new("error.type", eventData.Exception.Message)); 70 | } 71 | Activity.Current?.AddEvent(new ActivityEvent("redis command executed", 72 | DateTimeOffset.FromUnixTimeMilliseconds(eventData.OperationTimestamp!.Value), tags) 73 | ); 74 | 75 | Activity.Current?.Stop(); 76 | } 77 | break; 78 | } 79 | } 80 | } 81 | } -------------------------------------------------------------------------------- /src/FreeRedis.OpenTelemetry/DiagnosticSourceSubscriber.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading; 4 | 5 | namespace FreeRedis.OpenTelemetry 6 | { 7 | 8 | public class DiagnosticSourceSubscriber : IDisposable, IObserver 9 | { 10 | private readonly Func _diagnosticSourceFilter; 11 | private readonly Func _handlerFactory; 12 | private readonly Func? _isEnabledFilter; 13 | private readonly List _listenerSubscriptions; 14 | private IDisposable? _allSourcesSubscription; 15 | private long _disposed; 16 | 17 | public DiagnosticSourceSubscriber( 18 | DiagnosticListener handler, 19 | Func? isEnabledFilter) 20 | : this(_ => handler, 21 | value => FreeRedisDiagnosticListenerNames.DiagnosticListenerName == value.Name, 22 | isEnabledFilter) 23 | { 24 | } 25 | 26 | public DiagnosticSourceSubscriber( 27 | Func handlerFactory, 28 | Func diagnosticSourceFilter, 29 | Func? isEnabledFilter) 30 | { 31 | _listenerSubscriptions = new List(); 32 | _handlerFactory = handlerFactory ?? throw new ArgumentNullException(nameof(handlerFactory)); 33 | _diagnosticSourceFilter = diagnosticSourceFilter; 34 | _isEnabledFilter = isEnabledFilter; 35 | } 36 | 37 | /// 38 | public void Dispose() 39 | { 40 | Dispose(true); 41 | GC.SuppressFinalize(this); 42 | } 43 | 44 | public void OnNext(System.Diagnostics.DiagnosticListener value) 45 | { 46 | if (Interlocked.Read(ref _disposed) == 0 && _diagnosticSourceFilter(value)) 47 | { 48 | var handler = _handlerFactory(value.Name); 49 | var subscription = _isEnabledFilter == null 50 | ? value.Subscribe(handler) 51 | : value.Subscribe(handler, _isEnabledFilter); 52 | 53 | lock (_listenerSubscriptions) 54 | { 55 | _listenerSubscriptions.Add(subscription); 56 | } 57 | } 58 | } 59 | 60 | public void OnCompleted() 61 | { 62 | } 63 | 64 | public void OnError(Exception error) 65 | { 66 | } 67 | 68 | public void Subscribe() 69 | { 70 | _allSourcesSubscription ??= System.Diagnostics.DiagnosticListener.AllListeners.Subscribe(this); 71 | } 72 | 73 | protected virtual void Dispose(bool disposing) 74 | { 75 | if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 1) return; 76 | 77 | lock (_listenerSubscriptions) 78 | { 79 | foreach (var listenerSubscription in _listenerSubscriptions) 80 | { 81 | listenerSubscription?.Dispose(); 82 | } 83 | 84 | _listenerSubscriptions.Clear(); 85 | } 86 | 87 | _allSourcesSubscription?.Dispose(); 88 | _allSourcesSubscription = null; 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /src/FreeRedis.OpenTelemetry/FreeRedis.OpenTelemetry.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net80 5 | FreeRedis.OpenTelemetry 6 | FreeRedis.OpenTelemetry 7 | FreeRedis.OpenTelemetry 8 | 1.3.8 9 | true 10 | https://github.com/2881099/FreeRedis 11 | https://github.com/2881099/FreeRedis 12 | FreeRedis redis-trib cluster rediscluster sentinel OpenTelemetry 13 | git 14 | MIT 15 | $(AssemblyName) 16 | true 17 | true 18 | 3 19 | true 20 | key.snk 21 | false 22 | readme.md 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /src/FreeRedis.OpenTelemetry/FreeRedisInstrumentation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace FreeRedis.OpenTelemetry 4 | { 5 | 6 | public class FreeRedisInstrumentation : IDisposable 7 | { 8 | private readonly DiagnosticSourceSubscriber? _diagnosticSourceSubscriber; 9 | 10 | public FreeRedisInstrumentation(DiagnosticListener diagnosticListener) 11 | { 12 | _diagnosticSourceSubscriber = new DiagnosticSourceSubscriber(diagnosticListener, null); 13 | _diagnosticSourceSubscriber.Subscribe(); 14 | } 15 | 16 | /// 17 | public void Dispose() 18 | { 19 | _diagnosticSourceSubscriber?.Dispose(); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /src/FreeRedis.OpenTelemetry/TracerProviderBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using OpenTelemetry.Trace; 2 | using System; 3 | using System.Diagnostics; 4 | 5 | namespace FreeRedis.OpenTelemetry 6 | { 7 | 8 | public static class TracerProviderBuilderExtensions 9 | { 10 | public static TracerProviderBuilder AddFreeRedisInstrumentation(this TracerProviderBuilder builder, RedisClient redisClient) 11 | { 12 | if (builder == null) throw new ArgumentNullException(nameof(builder)); 13 | if (redisClient == null) throw new ArgumentNullException(nameof(redisClient)); 14 | 15 | redisClient.Notice += (s, e) => 16 | { 17 | if (Debugger.IsAttached) 18 | Debug.WriteLine(e.Log); 19 | }; 20 | 21 | builder.AddSource(DiagnosticListener.SourceName); 22 | 23 | var instrumentation = new FreeRedisInstrumentation(new DiagnosticListener()); 24 | 25 | return builder.AddInstrumentation(() => instrumentation); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /src/FreeRedis.OpenTelemetry/key.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2881099/FreeRedis/cc5bdb638a1035cc64b9bdc2778a2875cf46b1d9/src/FreeRedis.OpenTelemetry/key.snk -------------------------------------------------------------------------------- /src/FreeRedis/FreeRedis.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0;net451;net40 5 | FreeRedis 6 | FreeRedis 7 | FreeRedis 8 | 1.3.8 9 | true 10 | https://github.com/2881099/FreeRedis 11 | FreeRedis is .NET redis client, supports cluster, sentinel, master-slave, pipeline, transaction and connection pool. 12 | https://github.com/2881099/FreeRedis 13 | FreeRedis redis-trib cluster rediscluster sentinel 14 | git 15 | MIT 16 | $(AssemblyName) 17 | true 18 | true 19 | 3 20 | true 21 | key.snk 22 | false 23 | readme.md 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 8.0.1 33 | 34 | 35 | 36 | 37 | FreeRedis.xml 38 | 3 39 | 1701;1702;1591 40 | 41 | 42 | 43 | net40 44 | 45 | 46 | isasync 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /src/FreeRedis/FreeRedisDiagnosticListenerNames.cs: -------------------------------------------------------------------------------- 1 | namespace FreeRedis 2 | { 3 | public static class FreeRedisDiagnosticListenerNames 4 | { 5 | private const string FreeRedisPrefix = "FreeRedis."; 6 | 7 | //Tracing 8 | public const string DiagnosticListenerName = "FreeRedisDiagnosticListener"; 9 | 10 | public const string NoticeCallAfter = FreeRedisPrefix + "NoticeCallAfter"; 11 | public const string NoticeCallBefore = FreeRedisPrefix + "NoticeCallBefore"; 12 | } 13 | } -------------------------------------------------------------------------------- /src/FreeRedis/Internal/IRedisSocket.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Net; 6 | using System.Net.Sockets; 7 | using System.Text; 8 | using System.Text.RegularExpressions; 9 | using System.Threading; 10 | using System.Threading.Tasks; 11 | 12 | namespace FreeRedis.Internal 13 | { 14 | public interface IRedisSocket : IDisposable 15 | { 16 | string Host { get; } 17 | bool Ssl { get; } 18 | TimeSpan ConnectTimeout { get; set; } 19 | TimeSpan ReceiveTimeout { get; set; } 20 | TimeSpan SendTimeout { get; set; } 21 | 22 | Socket Socket { get; } 23 | Stream Stream { get; } 24 | bool IsConnected { get; } 25 | event EventHandler Connected; 26 | event EventHandler Disconnected; 27 | 28 | RedisProtocol Protocol { get; set; } 29 | Encoding Encoding { get; set; } 30 | 31 | CommandPacket LastCommand { get; } 32 | void Write(CommandPacket cmd); 33 | RedisResult Read(CommandPacket cmd); 34 | void ReadChunk(Stream destination, int bufferSize = 1024); 35 | #if isasync 36 | Task WriteAsync(CommandPacket cmd); 37 | Task ReadAsync(CommandPacket cmd); 38 | Task ReadChunkAsync(Stream destination, int bufferSize = 1024); 39 | #endif 40 | ClientReplyType ClientReply { get; } 41 | /// 42 | /// Redis-server ClientID 43 | /// 44 | long ClientId { get; } 45 | /// 46 | /// FreeRedis 本地专用 ID 47 | /// 48 | Guid ClientId2 { get; } 49 | int Database { get; } 50 | 51 | void Connect(); 52 | 53 | void ResetHost(string host); 54 | void ReleaseSocket(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/FreeRedis/Internal/IdleBus/IdleBus.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Text; 6 | using System.Threading; 7 | 8 | namespace FreeRedis.Internal 9 | { 10 | /// 11 | /// 空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题 12 | /// 13 | public class IdleBus : IdleBus 14 | { 15 | /// 16 | /// 按空闲时间1分钟,创建空闲容器 17 | /// 18 | public IdleBus() : base() { } 19 | /// 20 | /// 指定空闲时间、创建空闲容器 21 | /// 22 | /// 空闲时间 23 | public IdleBus(TimeSpan idle) : base(idle) { } 24 | } 25 | 26 | /// 27 | /// 空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题 28 | /// 29 | public class IdleBus : IdleBus where TValue : class, IDisposable 30 | { 31 | /// 32 | /// 按空闲时间1分钟,创建空闲容器 33 | /// 34 | public IdleBus() : base() { } 35 | /// 36 | /// 指定空闲时间、创建空闲容器 37 | /// 38 | /// 空闲时间 39 | public IdleBus(TimeSpan idle) : base(idle) { } 40 | } 41 | } -------------------------------------------------------------------------------- /src/FreeRedis/Internal/IdleBus/IdleBus`1.ItemInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Text; 6 | using System.Threading; 7 | 8 | namespace FreeRedis.Internal 9 | { 10 | partial class IdleBus 11 | { 12 | 13 | class ItemInfo : IDisposable 14 | { 15 | internal IdleBus ib; 16 | internal TKey key; 17 | internal Func create; 18 | internal TimeSpan idle; 19 | internal DateTime createTime; 20 | internal DateTime lastActiveTime; 21 | internal long activeCounter; 22 | internal int releaseErrorCounter; 23 | 24 | internal TValue value { get; private set; } 25 | internal TValue firstValue { get; private set; } 26 | internal bool IsRegisterError { get; private set; } 27 | object valueLock = new object(); 28 | 29 | internal TValue GetOrCreate() 30 | { 31 | if (isdisposed == true) return null; 32 | if (value == null) 33 | { 34 | var iscreate = false; 35 | var now = DateTime.Now; 36 | try 37 | { 38 | lock (valueLock) 39 | { 40 | if (isdisposed == true) return null; 41 | if (value == null) 42 | { 43 | value = create(); 44 | createTime = DateTime.Now; 45 | Interlocked.Increment(ref ib._usageQuantity); 46 | iscreate = true; 47 | } 48 | else 49 | { 50 | return value; 51 | } 52 | } 53 | if (iscreate) 54 | { 55 | if (value != null) 56 | { 57 | if (firstValue == null) firstValue = value; //记录首次值 58 | else if (firstValue == value) IsRegisterError = true; //第二次与首次相等,注册姿势错误 59 | } 60 | ib.OnNotice(new NoticeEventArgs(NoticeType.AutoCreate, key, null, $"{key} 实例+++创建成功,耗时 {DateTime.Now.Subtract(now).TotalMilliseconds}ms,{ib._usageQuantity}/{ib.Quantity}")); 61 | } 62 | } 63 | catch (Exception ex) 64 | { 65 | ib.OnNotice(new NoticeEventArgs(NoticeType.AutoCreate, key, ex, $"{key} 实例+++创建失败:{ex.Message}")); 66 | throw; 67 | } 68 | } 69 | lastActiveTime = DateTime.Now; 70 | Interlocked.Increment(ref activeCounter); 71 | return value; 72 | } 73 | 74 | internal bool Release(Func lockInIf) 75 | { 76 | lock (valueLock) 77 | { 78 | if (value != null && lockInIf()) 79 | { 80 | value?.Dispose(); 81 | value = null; 82 | Interlocked.Decrement(ref ib._usageQuantity); 83 | Interlocked.Exchange(ref activeCounter, 0); 84 | return true; 85 | } 86 | } 87 | return false; 88 | } 89 | 90 | ~ItemInfo() => Dispose(); 91 | bool isdisposed = false; 92 | public void Dispose() 93 | { 94 | if (isdisposed) return; 95 | lock (valueLock) 96 | { 97 | if (isdisposed) return; 98 | isdisposed = true; 99 | } 100 | try 101 | { 102 | Release(() => true); 103 | } 104 | catch { } 105 | } 106 | 107 | } 108 | 109 | } 110 | } -------------------------------------------------------------------------------- /src/FreeRedis/Internal/IdleBus/IdleBus`1.NoticeEventArgs.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Text; 6 | using System.Threading; 7 | 8 | namespace FreeRedis.Internal 9 | { 10 | partial class IdleBus 11 | { 12 | 13 | public class NoticeEventArgs : EventArgs 14 | { 15 | 16 | public NoticeType NoticeType { get; } 17 | public TKey Key { get; } 18 | public Exception Exception { get; } 19 | public string Log { get; } 20 | 21 | public NoticeEventArgs(NoticeType noticeType, TKey key, Exception exception, string log) 22 | { 23 | this.NoticeType = noticeType; 24 | this.Key = key; 25 | this.Exception = exception; 26 | this.Log = log; 27 | } 28 | 29 | } 30 | 31 | } 32 | } -------------------------------------------------------------------------------- /src/FreeRedis/Internal/IdleBus/IdleBus`1.NoticeType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Text; 6 | using System.Threading; 7 | 8 | namespace FreeRedis.Internal 9 | { 10 | partial class IdleBus 11 | { 12 | 13 | public enum NoticeType 14 | { 15 | 16 | /// 17 | /// 执行 Register 方法的时候 18 | /// 19 | Register, 20 | 21 | /// 22 | /// 执行 Remove 方法的时候,注意:实际会延时释放【实例】 23 | /// 24 | Remove, 25 | 26 | /// 27 | /// 自动创建【实例】的时候 28 | /// 29 | AutoCreate, 30 | 31 | /// 32 | /// 自动释放不活跃【实例】的时候 33 | /// 34 | AutoRelease, 35 | 36 | /// 37 | /// 获取【实例】的时候 38 | /// 39 | Get 40 | 41 | } 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /src/FreeRedis/Internal/IdleBus/IdleBus`1.Test.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Text; 6 | using System.Threading; 7 | 8 | namespace FreeRedis.Internal 9 | { 10 | partial class IdleBus 11 | { 12 | 13 | public static void Test() 14 | { 15 | //超过1分钟没有使用,连续检测2次都这样,就销毁【实例】 16 | var ib = new IdleBus(TimeSpan.FromMinutes(1)); 17 | ib.Notice += (_, e) => 18 | { 19 | var log = $"[{DateTime.Now.ToString("HH:mm:ss")}] 线程{Thread.CurrentThread.ManagedThreadId}:{e.Log}"; 20 | //Trace.WriteLine(log); 21 | Console.WriteLine(log); 22 | }; 23 | 24 | ib.Register("key1", () => new ManualResetEvent(false)); 25 | ib.Register("key2", () => new AutoResetEvent(false)); 26 | 27 | var item = ib.Get("key2") as AutoResetEvent; 28 | //获得 key2 对象,创建 29 | 30 | item = ib.Get("key2") as AutoResetEvent; 31 | //获得 key2 对象,已创建 32 | 33 | int num1 = ib.UsageQuantity; 34 | //【实例】有效数量(即已经创建了的),后台定时清理不活跃的【实例】,此值就会减少 35 | 36 | ib.Dispose(); 37 | } 38 | 39 | } 40 | } -------------------------------------------------------------------------------- /src/FreeRedis/Internal/IdleBus/IdleBus`1.ThreadScan.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading; 8 | 9 | namespace FreeRedis.Internal 10 | { 11 | partial class IdleBus 12 | { 13 | bool _threadStarted = false; 14 | object _threadStartedLock = new object(); 15 | 16 | void ThreadScanWatch(ItemInfo item) 17 | { 18 | var startThread = false; 19 | if (_threadStarted == false) 20 | lock (_threadStartedLock) 21 | if (_threadStarted == false) 22 | startThread = _threadStarted = true; 23 | 24 | if (startThread) 25 | new Thread(() => 26 | { 27 | this.ThreadScanWatchHandler(); 28 | lock (_threadStartedLock) 29 | _threadStarted = false; 30 | }).Start(); 31 | } 32 | 33 | 34 | public class TimeoutScanOptions 35 | { 36 | /// 37 | /// 扫描线程间隔(默认值:2秒) 38 | /// 39 | public TimeSpan Interval { get; set; } = TimeSpan.FromSeconds(2); 40 | /// 41 | /// 扫描线程空闲多少秒退出(默认值:10秒) 42 | /// 43 | public int QuitWaitSeconds { get; set; } = 10; 44 | /// 45 | /// 扫描的每批数量(默认值:512) 46 | /// 可防止注册数量太多时导致 CPU 占用过高 47 | /// 48 | public int BatchQuantity { get; set; } = 512; 49 | /// 50 | /// 达到扫描的每批数量时,线程等待(默认值:1秒) 51 | /// 52 | public TimeSpan BatchQuantityWait { get; set; } = TimeSpan.FromSeconds(1); 53 | } 54 | /// 55 | /// 扫描过期对象的设置 56 | /// 机制:当窗口里有存活对象时,扫描线程才会开启(只开启一个线程)。 57 | /// 连续多少秒都没存活的对象时,才退出扫描。 58 | /// 59 | public TimeoutScanOptions ScanOptions { get; } = new TimeoutScanOptions(); 60 | 61 | void ThreadScanWatchHandler() 62 | { 63 | var couter = 0; 64 | while (IsDisposed == false) 65 | { 66 | if (ThreadJoin(ScanOptions.Interval) == false) return; 67 | this.InternalRemoveDelayHandler(); 68 | 69 | if (_usageQuantity == 0) 70 | { 71 | couter = couter + (int)ScanOptions.Interval.TotalSeconds; 72 | if (couter < ScanOptions.QuitWaitSeconds) continue; 73 | break; 74 | } 75 | couter = 0; 76 | 77 | var keys = _dic.Keys.ToArray(); 78 | long keysIndex = 0; 79 | foreach (var key in keys) 80 | { 81 | if (IsDisposed) return; 82 | ++keysIndex; 83 | if (ScanOptions.BatchQuantity > 0 && keysIndex % ScanOptions.BatchQuantity == 0) 84 | { 85 | if (ThreadJoin(ScanOptions.BatchQuantityWait) == false) return; 86 | } 87 | 88 | if (_dic.TryGetValue(key, out var item) == false) continue; 89 | if (item.value == null) continue; 90 | if (DateTime.Now.Subtract(item.lastActiveTime) <= item.idle) continue; 91 | try 92 | { 93 | var now = DateTime.Now; 94 | if (item.Release(() => DateTime.Now.Subtract(item.lastActiveTime) > item.idle && item.lastActiveTime >= item.createTime)) 95 | //防止并发有其他线程创建,最后活动时间 > 创建时间 96 | this.OnNotice(new NoticeEventArgs(NoticeType.AutoRelease, item.key, null, $"{key} ---自动释放成功,耗时 {DateTime.Now.Subtract(now).TotalMilliseconds}ms,{_usageQuantity}/{Quantity}")); 97 | } 98 | catch (Exception ex) 99 | { 100 | this.OnNotice(new NoticeEventArgs(NoticeType.AutoRelease, item.key, ex, $"{key} ---自动释放执行出错:{ex.Message}")); 101 | } 102 | } 103 | } 104 | } 105 | 106 | bool ThreadJoin(TimeSpan interval) 107 | { 108 | if (interval <= TimeSpan.Zero) return true; 109 | var milliseconds = interval.TotalMilliseconds; 110 | var seconds = Math.Floor(milliseconds / 1000); 111 | milliseconds = milliseconds - seconds * 1000; 112 | 113 | for (var a = 0; a < seconds; a++) 114 | { 115 | Thread.CurrentThread.Join(TimeSpan.FromSeconds(1)); 116 | if (IsDisposed) return false; 117 | } 118 | for (var a = 0; a < milliseconds; a += 200) 119 | { 120 | Thread.CurrentThread.Join(TimeSpan.FromMilliseconds(200)); 121 | if (IsDisposed) return false; 122 | } 123 | return true; 124 | } 125 | } 126 | } -------------------------------------------------------------------------------- /src/FreeRedis/Internal/ObjectPool/DefaultPolicy.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | 4 | namespace FreeRedis.Internal.ObjectPool 5 | { 6 | 7 | public class DefaultPolicy : IPolicy 8 | { 9 | 10 | public string Name { get; set; } = typeof(DefaultPolicy).GetType().FullName; 11 | public int PoolSize { get; set; } = 1000; 12 | public TimeSpan SyncGetTimeout { get; set; } = TimeSpan.FromSeconds(10); 13 | public TimeSpan IdleTimeout { get; set; } = TimeSpan.FromSeconds(50); 14 | public int AsyncGetCapacity { get; set; } = 10000; 15 | public bool IsThrowGetTimeoutException { get; set; } = true; 16 | public bool IsAutoDisposeWithSystem { get; set; } = true; 17 | public int CheckAvailableInterval { get; set; } = 3; 18 | 19 | public Func CreateObject; 20 | public Action> OnGetObject; 21 | 22 | public T OnCreate() 23 | { 24 | return CreateObject(); 25 | } 26 | 27 | public void OnDestroy(T obj) 28 | { 29 | 30 | } 31 | 32 | public void OnGet(Object obj) 33 | { 34 | OnGetObject?.Invoke(obj); 35 | } 36 | 37 | #if net40 38 | #else 39 | public Task OnGetAsync(Object obj) 40 | { 41 | OnGetObject?.Invoke(obj); 42 | return Task.FromResult(true); 43 | } 44 | #endif 45 | 46 | public void OnGetTimeout() 47 | { 48 | 49 | } 50 | 51 | public void OnReturn(Object obj) 52 | { 53 | } 54 | 55 | public bool OnCheckAvailable(Object obj) 56 | { 57 | return true; 58 | } 59 | 60 | public void OnAvailable() 61 | { 62 | 63 | } 64 | 65 | public void OnUnavailable() 66 | { 67 | 68 | } 69 | } 70 | } -------------------------------------------------------------------------------- /src/FreeRedis/Internal/ObjectPool/IObjectPool.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | 4 | namespace FreeRedis.Internal.ObjectPool 5 | { 6 | public interface IObjectPool : IDisposable 7 | { 8 | IPolicy Policy { get; } 9 | /// 10 | /// 是否可用 11 | /// 12 | bool IsAvailable { get; } 13 | /// 14 | /// 不可用错误 15 | /// 16 | Exception UnavailableException { get; } 17 | /// 18 | /// 不可用时间 19 | /// 20 | DateTime? UnavailableTime { get; } 21 | 22 | /// 23 | /// 将对象池设置为不可用,后续 Get/GetAsync 均会报错,同时启动后台定时检查服务恢复可用 24 | /// 25 | /// 26 | /// 27 | /// 由【可用】变成【不可用】时返回true,否则返回false 28 | bool SetUnavailable(Exception exception, DateTime lastGetTime); 29 | 30 | /// 31 | /// 统计对象池中的对象 32 | /// 33 | string Statistics { get; } 34 | /// 35 | /// 统计对象池中的对象(完整) 36 | /// 37 | string StatisticsFullily { get; } 38 | 39 | /// 40 | /// 获取资源 41 | /// 42 | /// 超时 43 | /// 44 | Object Get(TimeSpan? timeout = null); 45 | 46 | #if net40 47 | #else 48 | /// 49 | /// 获取资源 50 | /// 51 | /// 52 | Task> GetAsync(); 53 | #endif 54 | 55 | /// 56 | /// 使用完毕后,归还资源 57 | /// 58 | /// 对象 59 | /// 是否重新创建 60 | void Return(Object obj, bool isReset = false); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/FreeRedis/Internal/ObjectPool/IPolicy.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | 4 | namespace FreeRedis.Internal.ObjectPool 5 | { 6 | public interface IPolicy 7 | { 8 | 9 | /// 10 | /// 名称 11 | /// 12 | string Name { get; set; } 13 | 14 | /// 15 | /// 池容量 16 | /// 17 | int PoolSize { get; set; } 18 | 19 | /// 20 | /// 默认获取超时设置 21 | /// 22 | TimeSpan SyncGetTimeout { get; set; } 23 | 24 | /// 25 | /// 空闲时间,获取时若超出,则重新创建 26 | /// 27 | TimeSpan IdleTimeout { get; set; } 28 | 29 | /// 30 | /// 异步获取排队队列大小,小于等于0不生效 31 | /// 32 | int AsyncGetCapacity { get; set; } 33 | 34 | /// 35 | /// 获取超时后,是否抛出异常 36 | /// 37 | bool IsThrowGetTimeoutException { get; set; } 38 | 39 | /// 40 | /// 监听 AppDomain.CurrentDomain.ProcessExit/Console.CancelKeyPress 事件自动释放 41 | /// 42 | bool IsAutoDisposeWithSystem { get; set; } 43 | 44 | /// 45 | /// 后台定时检查可用性间隔秒数 46 | /// 47 | int CheckAvailableInterval { get; set; } 48 | 49 | /// 50 | /// 对象池的对象被创建时 51 | /// 52 | /// 返回被创建的对象 53 | T OnCreate(); 54 | 55 | /// 56 | /// 销毁对象 57 | /// 58 | /// 资源对象 59 | void OnDestroy(T obj); 60 | 61 | /// 62 | /// 从对象池获取对象超时的时候触发,通过该方法统计 63 | /// 64 | void OnGetTimeout(); 65 | 66 | /// 67 | /// 从对象池获取对象成功的时候触发,通过该方法统计或初始化对象 68 | /// 69 | /// 资源对象 70 | void OnGet(Object obj); 71 | #if net40 72 | #else 73 | /// 74 | /// 从对象池获取对象成功的时候触发,通过该方法统计或初始化对象 75 | /// 76 | /// 资源对象 77 | Task OnGetAsync(Object obj); 78 | #endif 79 | 80 | /// 81 | /// 归还对象给对象池的时候触发 82 | /// 83 | /// 资源对象 84 | void OnReturn(Object obj); 85 | 86 | /// 87 | /// 检查可用性 88 | /// 89 | /// 资源对象 90 | /// 91 | bool OnCheckAvailable(Object obj); 92 | 93 | /// 94 | /// 事件:可用时触发 95 | /// 96 | void OnAvailable(); 97 | /// 98 | /// 事件:不可用时触发 99 | /// 100 | void OnUnavailable(); 101 | } 102 | } -------------------------------------------------------------------------------- /src/FreeRedis/Internal/ObjectPool/Object.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | 4 | namespace FreeRedis.Internal.ObjectPool 5 | { 6 | 7 | public class Object : IDisposable 8 | { 9 | public static Object InitWith(IObjectPool pool, int id, T value) 10 | { 11 | return new Object 12 | { 13 | Pool = pool, 14 | Id = id, 15 | Value = value, 16 | LastGetThreadId = Thread.CurrentThread.ManagedThreadId, 17 | LastGetTime = DateTime.Now, 18 | LastGetTimeCopy = DateTime.Now 19 | }; 20 | } 21 | 22 | /// 23 | /// 所属对象池 24 | /// 25 | public IObjectPool Pool { get; internal set; } 26 | 27 | /// 28 | /// 在对象池中的唯一标识 29 | /// 30 | public int Id { get; internal set; } 31 | /// 32 | /// 资源对象 33 | /// 34 | public T Value { get; internal set; } 35 | 36 | internal long _getTimes; 37 | /// 38 | /// 被获取的总次数 39 | /// 40 | public long GetTimes => _getTimes; 41 | 42 | /// 最后获取时的时间 43 | public DateTime LastGetTime { get; internal set; } 44 | public DateTime LastGetTimeCopy { get; internal set; } 45 | 46 | /// 47 | /// 最后归还时的时间 48 | /// 49 | public DateTime LastReturnTime { get; internal set; } 50 | 51 | /// 52 | /// 创建时间 53 | /// 54 | public DateTime CreateTime { get; internal set; } = DateTime.Now; 55 | 56 | /// 57 | /// 最后获取时的线程id 58 | /// 59 | public int LastGetThreadId { get; internal set; } 60 | 61 | /// 62 | /// 最后归还时的线程id 63 | /// 64 | public int LastReturnThreadId { get; internal set; } 65 | 66 | public override string ToString() 67 | { 68 | return $"{this.Value}, Times: {this.GetTimes}, ThreadId(R/G): {this.LastReturnThreadId}/{this.LastGetThreadId}, Time(R/G): {this.LastReturnTime.ToString("yyyy-MM-dd HH:mm:ss:ms")}/{this.LastGetTime.ToString("yyyy-MM-dd HH:mm:ss:ms")}"; 69 | } 70 | 71 | /// 72 | /// 重置 Value 值 73 | /// 74 | public void ResetValue() 75 | { 76 | if (this.Value != null) 77 | { 78 | try { this.Pool.Policy.OnDestroy(this.Value); } catch { } 79 | try { (this.Value as IDisposable)?.Dispose(); } catch { } 80 | } 81 | T value = default(T); 82 | try { value = this.Pool.Policy.OnCreate(); } catch { } 83 | this.Value = value; 84 | this.LastReturnTime = DateTime.Now; 85 | } 86 | 87 | internal bool _isReturned = false; 88 | public void Dispose() 89 | { 90 | Pool?.Return(this); 91 | } 92 | } 93 | } -------------------------------------------------------------------------------- /src/FreeRedis/Internal/TempDisposable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace FreeRedis.Internal 6 | { 7 | class TempDisposable : IDisposable 8 | { 9 | Action _release; 10 | public TempDisposable(Action release) 11 | { 12 | _release = release; 13 | } 14 | 15 | public void Dispose() => _release?.Invoke(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/FreeRedis/Internal/_net40.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace FreeRedis 8 | { 9 | internal static class TaskEx 10 | { 11 | public static Task FromResult(T value) 12 | { 13 | #if net40 14 | return new Task(() => value); 15 | #else 16 | return Task.FromResult(value); 17 | #endif 18 | } 19 | public static Task Run(Action action) 20 | { 21 | #if net40 22 | var tcs = new TaskCompletionSource(); 23 | new Thread(() => 24 | { 25 | try 26 | { 27 | action(); 28 | tcs.SetResult(null); 29 | } 30 | catch (Exception ex) 31 | { 32 | tcs.SetException(ex); 33 | } 34 | }) 35 | { IsBackground = true }.Start(); 36 | return tcs.Task; 37 | #else 38 | return Task.Run(action); 39 | #endif 40 | } 41 | public static Task Run(Func function) 42 | { 43 | var tcs = new TaskCompletionSource(); 44 | new Thread(() => 45 | { 46 | try 47 | { 48 | tcs.SetResult(function()); 49 | } 50 | catch (Exception ex) 51 | { 52 | tcs.SetException(ex); 53 | } 54 | }) 55 | { IsBackground = true }.Start(); 56 | return tcs.Task; 57 | } 58 | public static Task Delay(TimeSpan timeout) 59 | { 60 | var tcs = new TaskCompletionSource(); 61 | var timer = new System.Timers.Timer(timeout.TotalMilliseconds) { AutoReset = false }; 62 | timer.Elapsed += delegate { timer.Dispose(); tcs.SetResult(null); }; 63 | timer.Start(); 64 | return tcs.Task; 65 | } 66 | 67 | #if !NET40 68 | public static async Task TimeoutAfter(this Task task, TimeSpan timeout, string message = "The operation has timed out.") 69 | { 70 | using (var timeoutCancellationTokenSource = new CancellationTokenSource()) 71 | { 72 | var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token)); 73 | if (completedTask == task) 74 | { 75 | timeoutCancellationTokenSource.Cancel(); 76 | return await task; 77 | } 78 | else 79 | { 80 | throw new TimeoutException(message); 81 | } 82 | } 83 | } 84 | 85 | public static async Task TimeoutAfter(this Task task, TimeSpan timeout, string message = "The operation has timed out.") 86 | { 87 | using (var timeoutCancellationTokenSource = new CancellationTokenSource()) 88 | { 89 | var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token)); 90 | if (completedTask == task) 91 | { 92 | timeoutCancellationTokenSource.Cancel(); 93 | await task; 94 | } 95 | else 96 | { 97 | throw new TimeoutException(message); 98 | } 99 | } 100 | } 101 | #endif 102 | } 103 | } -------------------------------------------------------------------------------- /src/FreeRedis/RedisClient/Adapter/BaseAdapter.cs: -------------------------------------------------------------------------------- 1 | using FreeRedis.Internal; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace FreeRedis 9 | { 10 | partial class RedisClient 11 | { 12 | protected internal enum UseType 13 | { 14 | Pooling, 15 | Cluster, 16 | Sentinel, 17 | SingleInside, 18 | SingleTemp, 19 | 20 | Pipeline, 21 | Transaction, 22 | } 23 | 24 | protected internal abstract partial class BaseAdapter 25 | { 26 | public static ThreadLocal _rnd = new ThreadLocal(() => new Random()); 27 | public UseType UseType { get; protected set; } 28 | protected internal RedisClient TopOwner { get; protected set; } 29 | 30 | public abstract void Refersh(IRedisSocket redisSocket); 31 | public abstract IRedisSocket GetRedisSocket(CommandPacket cmd); 32 | public abstract void Dispose(); 33 | 34 | public abstract TValue AdapterCall(CommandPacket cmd, Func parse); 35 | 36 | #if isasync 37 | public abstract Task AdapterCallAsync(CommandPacket cmd, Func parse); 38 | #endif 39 | 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/FreeRedis/RedisClient/Adapter/SingleInsideAdapter.cs: -------------------------------------------------------------------------------- 1 | using FreeRedis.Internal; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Net; 6 | using System.Net.Security; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace FreeRedis 11 | { 12 | partial class RedisClient 13 | { 14 | internal class SingleInsideAdapter : BaseAdapter 15 | { 16 | readonly IRedisSocket _redisSocket; 17 | 18 | public SingleInsideAdapter(RedisClient topOwner, RedisClient owner, string host, 19 | bool ssl, RemoteCertificateValidationCallback certificateValidation, LocalCertificateSelectionCallback certificateSelection, 20 | TimeSpan connectTimeout, TimeSpan receiveTimeout, TimeSpan sendTimeout, 21 | Action connected, Action disconnected) 22 | { 23 | UseType = UseType.SingleInside; 24 | TopOwner = topOwner; 25 | _redisSocket = new DefaultRedisSocket(host, ssl, certificateValidation, certificateSelection); 26 | _redisSocket.Connected += (s, e) => connected?.Invoke(owner); 27 | _redisSocket.Disconnected += (s, e) => disconnected?.Invoke(owner); 28 | _redisSocket.ConnectTimeout = connectTimeout; 29 | _redisSocket.ReceiveTimeout = receiveTimeout; 30 | _redisSocket.SendTimeout = sendTimeout; 31 | } 32 | 33 | public override void Dispose() 34 | { 35 | _redisSocket.Dispose(); 36 | } 37 | 38 | public override void Refersh(IRedisSocket redisSocket) 39 | { 40 | } 41 | public override IRedisSocket GetRedisSocket(CommandPacket cmd) 42 | { 43 | return DefaultRedisSocket.CreateTempProxy(_redisSocket, null); 44 | } 45 | public override TValue AdapterCall(CommandPacket cmd, Func parse) 46 | { 47 | return TopOwner.LogCall(cmd, () => 48 | { 49 | _redisSocket.Write(cmd); 50 | var rt = _redisSocket.Read(cmd); 51 | if (cmd._command == "QUIT") _redisSocket.ReleaseSocket(); 52 | return parse(rt); 53 | }); 54 | } 55 | #if isasync 56 | public override Task AdapterCallAsync(CommandPacket cmd, Func parse) 57 | { 58 | return TopOwner.LogCallAsync(cmd, async () => 59 | { 60 | await _redisSocket.WriteAsync(cmd); 61 | var rt = await _redisSocket.ReadAsync(cmd); 62 | if (cmd._command == "QUIT") _redisSocket.ReleaseSocket(); 63 | return parse(rt); 64 | }); 65 | } 66 | #endif 67 | 68 | } 69 | } 70 | } -------------------------------------------------------------------------------- /src/FreeRedis/RedisClient/Adapter/SingleTempAdapter.cs: -------------------------------------------------------------------------------- 1 | using FreeRedis.Internal; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Net; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace FreeRedis 10 | { 11 | partial class RedisClient 12 | { 13 | // GetDatabase 14 | public DatabaseHook GetDatabase(int? index = null) 15 | { 16 | CheckUseTypeOrThrow(UseType.Pooling, UseType.Sentinel); 17 | var rds = Adapter.GetRedisSocket(null); 18 | DatabaseHook hook = null; 19 | try 20 | { 21 | var oldindex = rds.Database; 22 | hook = new DatabaseHook(new SingleTempAdapter(Adapter.TopOwner, rds, () => 23 | { 24 | try 25 | { 26 | if (index != null) hook.Select(oldindex); 27 | } 28 | finally 29 | { 30 | rds.Dispose(); 31 | } 32 | })); 33 | if (index != null) hook.Select(index.Value); 34 | } 35 | catch 36 | { 37 | rds.Dispose(); 38 | throw; 39 | } 40 | return hook; 41 | } 42 | public class DatabaseHook : RedisClient 43 | { 44 | internal DatabaseHook(BaseAdapter adapter) : base(adapter) { } 45 | } 46 | 47 | class SingleTempAdapter : BaseAdapter 48 | { 49 | readonly IRedisSocket _redisSocket; 50 | readonly Action _dispose; 51 | 52 | public SingleTempAdapter(RedisClient topOwner, IRedisSocket redisSocket, Action dispose) 53 | { 54 | UseType = UseType.SingleInside; 55 | TopOwner = topOwner; 56 | _redisSocket = redisSocket; 57 | _dispose = dispose; 58 | } 59 | 60 | public override void Dispose() 61 | { 62 | _dispose?.Invoke(); 63 | } 64 | 65 | public override void Refersh(IRedisSocket redisSocket) 66 | { 67 | } 68 | public override IRedisSocket GetRedisSocket(CommandPacket cmd) 69 | { 70 | return DefaultRedisSocket.CreateTempProxy(_redisSocket, null); 71 | } 72 | public override TValue AdapterCall(CommandPacket cmd, Func parse) 73 | { 74 | return TopOwner.LogCall(cmd, () => 75 | { 76 | _redisSocket.Write(cmd); 77 | var rt = _redisSocket.Read(cmd); 78 | if (cmd._command == "QUIT") _redisSocket.ReleaseSocket(); 79 | return parse(rt); 80 | }); 81 | } 82 | #if isasync 83 | public override Task AdapterCallAsync(CommandPacket cmd, Func parse) 84 | { 85 | return TopOwner.LogCallAsync(cmd, async () => 86 | { 87 | await _redisSocket.WriteAsync(cmd); 88 | var rt = await _redisSocket.ReadAsync(cmd); 89 | if (cmd._command == "QUIT") _redisSocket.ReleaseSocket(); 90 | return parse(rt); 91 | }); 92 | } 93 | #endif 94 | 95 | } 96 | } 97 | } -------------------------------------------------------------------------------- /src/FreeRedis/RedisClient/Cluster.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | 6 | namespace FreeRedis 7 | { 8 | partial class RedisClient 9 | { 10 | //wait testing 11 | 12 | //public string ClusterAddSlots(params int[] slot) => Call("CLUSTER".SubCommand("ADDSLOTS").Input(slot), rt => rt.ThrowOrValue()); 13 | //public string ClusterBumpEpoch() => Call("CLUSTER".SubCommand("BUMPEPOCH"), rt => rt.ThrowOrValue()); 14 | //public long ClusterCountFailureReports(string nodeid) => Call("CLUSTER".SubCommand("COUNT-FAILURE-REPORTS").InputRaw(nodeid), rt => rt.ThrowOrValue()); 15 | 16 | //public long ClusterCountKeysInSlot(int slot) => Call("CLUSTER".SubCommand("COUNTKEYSINSLOT").InputRaw(slot), rt => rt.ThrowOrValue()); 17 | //public string ClusterDelSlots(params int[] slot) => Call("CLUSTER".SubCommand("DELSLOTS").Input(slot), rt => rt.ThrowOrValue()); 18 | //public string ClusterFailOver(ClusterFailOverType type) => Call("CLUSTER".SubCommand("FAILOVER").InputRaw(type), rt => rt.ThrowOrValue()); 19 | //public string ClusterFlushSlots() => Call("CLUSTER".SubCommand("FLUSHSLOTS"), rt => rt.ThrowOrValue()); 20 | 21 | //public long ClusterForget(string nodeid) => Call("CLUSTER".SubCommand("FORGET").InputRaw(nodeid), rt => rt.ThrowOrValue()); 22 | //public string[] ClusterGetKeysInSlot(int slot) => Call("CLUSTER".SubCommand("GETKEYSINSLOT").InputRaw(slot), rt => rt.ThrowOrValue()); 23 | //public Dictionary ClusterInfo() => Call("CLUSTER".SubCommand("INFO"), rt => rt.ThrowOrValue((a, _) => a.MapToHash(rt.Encoding))); 24 | 25 | //public int ClusterKeySlot(string key) => Call("CLUSTER".SubCommand("KEYSLOT").InputRaw(key), rt => rt.ThrowOrValue()); 26 | //public string ClusterMeet(string ip, int port) => Call("CLUSTER".SubCommand("MEET").Input(ip, port), rt => rt.ThrowOrValue()); 27 | //public string ClusterMyId() => Call("CLUSTER".SubCommand("MYID"), rt => rt.ThrowOrValue()); 28 | //public string ClusterNodes() => Call("CLUSTER".SubCommand("NODES"), rt => rt.ThrowOrValue()); 29 | 30 | //public string ClusterReplicas(string nodeid) => Call("CLUSTER".SubCommand("REPLICAS").InputRaw(nodeid), rt => rt.ThrowOrValue()); 31 | //public string ClusterReplicate(string nodeid) => Call("CLUSTER".SubCommand("REPLICATE").InputRaw(nodeid), rt => rt.ThrowOrValue()); 32 | //public string ClusterReset(ClusterResetType type) => Call("CLUSTER".SubCommand("RESET").InputRaw(type), rt => rt.ThrowOrValue()); 33 | //public string ClusterSaveConfig() => Call("CLUSTER".SubCommand("SAVECONFIG"), rt => rt.ThrowOrValue()); 34 | 35 | //public string ClusterSetConfigEpoch(string epoch) => Call("CLUSTER".SubCommand("SET-CONFIG-EPOCH").InputRaw(epoch), rt => rt.ThrowOrValue()); 36 | //public string[] ClusterSetSlot(int slot, ClusterSetSlotType type, string nodeid = null) => Call("CLUSTER".SubCommand("SETSLOT") 37 | // .Input(slot, type) 38 | // .InputIf(!string.IsNullOrWhiteSpace(nodeid), nodeid), rt => rt.ThrowOrValue()); 39 | 40 | //public string ClusterSlaves(string nodeid) => Call("CLUSTER".SubCommand("SLAVES").InputRaw(nodeid), rt => rt.ThrowOrValue()); 41 | //public object ClusterSlots() => Call("CLUSTER".SubCommand("SLOTS"), rt => rt.ThrowOrValue()); 42 | //public string ReadOnly() => Call("READONLY", rt => rt.ThrowOrValue()); 43 | //public string ReadWrite() => Call("READWRITE", rt => rt.ThrowOrValue()); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/FreeRedis/RedisClient/HyperLogLog.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace FreeRedis 8 | { 9 | partial class RedisClient 10 | { 11 | #if isasync 12 | #region async (copy from sync) 13 | public Task PfAddAsync(string key, params object[] elements) => CallAsync("PFADD".InputKey(key).Input(elements.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue()); 14 | public Task PfCountAsync(params string[] keys) => CallAsync("PFCOUNT".InputKey(keys), rt => rt.ThrowOrValue()); 15 | public Task PfMergeAsync(string destkey, params string[] sourcekeys) => CallAsync("PFMERGE".InputKey(destkey).InputKey(sourcekeys), rt => rt.ThrowOrValue()); 16 | #endregion 17 | #endif 18 | 19 | public bool PfAdd(string key, params object[] elements) => Call("PFADD".InputKey(key).Input(elements.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue()); 20 | public long PfCount(params string[] keys) => Call("PFCOUNT".InputKey(keys), rt => rt.ThrowOrValue()); 21 | public void PfMerge(string destkey, params string[] sourcekeys) => Call("PFMERGE".InputKey(destkey).InputKey(sourcekeys), rt => rt.ThrowOrValue()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/FreeRedis/RedisClient/Modules/BloomFilter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace FreeRedis 8 | { 9 | partial class RedisClient 10 | { 11 | #if isasync 12 | #region async (copy from sync) 13 | 14 | public Task BfReserveAsync(string key, decimal errorRate, long capacity, int expansion = 2, bool nonScaling = false) => CallAsync("BF.RESERVE" 15 | .InputKey(key) 16 | .Input(errorRate, capacity) 17 | .InputIf(expansion != 2, "EXPANSION", expansion) 18 | .InputIf(nonScaling, "NONSCALING"), rt => rt.ThrowOrValue()); 19 | public Task BfAddAsync(string key, string item) => CallAsync("BF.ADD".InputKey(key, item), rt => rt.ThrowOrValue()); 20 | public Task BfMAddAsync(string key, string[] items) => CallAsync("BF.MADD".InputKey(key, items), rt => rt.ThrowOrValue()); 21 | 22 | public Task BfInsertAsync(string key, string[] items, long? capacity = null, string error = null, int expansion = 2, bool noCreate = false, bool nonScaling = false) => CallAsync("BF.INSERT" 23 | .InputKey(key) 24 | .InputIf(capacity != null, "CAPACITY", capacity) 25 | .InputIf(!string.IsNullOrWhiteSpace(error), "ERROR", error) 26 | .InputIf(expansion != 2, "EXPANSION", expansion) 27 | .InputIf(noCreate, "NOCREATE") 28 | .InputIf(nonScaling, "NONSCALING") 29 | .Input("ITEMS", items), rt => rt.ThrowOrValue()); 30 | 31 | public Task BfExistsAsync(string key, string item) => CallAsync("BF.EXISTS".InputKey(key, item), rt => rt.ThrowOrValue()); 32 | public Task BfMExistsAsync(string key, string[] items) => CallAsync("BF.MEXISTS".InputKey(key, items), rt => rt.ThrowOrValue()); 33 | public Task> BfScanDumpAsync(string key, long iter) => CallAsync("BF.SCANDUMP".InputKey(key, iter), rt => rt.ThrowOrValue((a, _) => 34 | new ScanResult(a[0].ConvertTo(), a[1].ConvertTo()))); 35 | 36 | public Task BfLoadChunkAsync(string key, long iter, byte[] data) => CallAsync("BF.LOADCHUNK".InputKey(key, iter).InputRaw(data), rt => rt.ThrowOrValue()); 37 | public Task> BfInfoAsync(string key) => CallAsync("BF.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash(rt.Encoding))); 38 | 39 | #endregion 40 | #endif 41 | 42 | public string BfReserve(string key, decimal errorRate, long capacity, int expansion = 2, bool nonScaling = false) => Call("BF.RESERVE" 43 | .InputKey(key) 44 | .Input(errorRate, capacity) 45 | .InputIf(expansion != 2, "EXPANSION", expansion) 46 | .InputIf(nonScaling, "NONSCALING"), rt => rt.ThrowOrValue()); 47 | public bool BfAdd(string key, string item) => Call("BF.ADD".InputKey(key, item), rt => rt.ThrowOrValue()); 48 | public bool[] BfMAdd(string key, string[] items) => Call("BF.MADD".InputKey(key, items), rt => rt.ThrowOrValue()); 49 | 50 | public string BfInsert(string key, string[] items, long? capacity = null, string error = null, int expansion = 2, bool noCreate = false, bool nonScaling = false) => Call("BF.INSERT" 51 | .InputKey(key) 52 | .InputIf(capacity != null, "CAPACITY", capacity) 53 | .InputIf(!string.IsNullOrWhiteSpace(error), "ERROR", error) 54 | .InputIf(expansion != 2, "EXPANSION", expansion) 55 | .InputIf(noCreate, "NOCREATE") 56 | .InputIf(nonScaling, "NONSCALING") 57 | .Input("ITEMS", items), rt => rt.ThrowOrValue()); 58 | 59 | public bool BfExists(string key, string item) => Call("BF.EXISTS".InputKey(key, item), rt => rt.ThrowOrValue()); 60 | public bool[] BfMExists(string key, string[] items) => Call("BF.MEXISTS".InputKey(key, items), rt => rt.ThrowOrValue()); 61 | public ScanResult BfScanDump(string key, long iter) => Call("BF.SCANDUMP".InputKey(key, iter), rt => rt.ThrowOrValue((a, _) => 62 | new ScanResult(a[0].ConvertTo(), a[1].ConvertTo()))); 63 | 64 | public string BfLoadChunk(string key, long iter, byte[] data) => Call("BF.LOADCHUNK".InputKey(key, iter).InputRaw(data), rt => rt.ThrowOrValue()); 65 | public Dictionary BfInfo(string key) => Call("BF.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash(rt.Encoding))); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/FreeRedis/RedisClient/Modules/CRC16.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace FreeRedis 8 | { 9 | partial class RedisClient 10 | { 11 | public FreeRedisClusterCRC16 ClusterCRC16 = new FreeRedisClusterCRC16(); 12 | } 13 | 14 | public class FreeRedisClusterCRC16 15 | { 16 | private int[] LOOKUP_TABLE = new int[] 17 | { 18 | 0, 4129, 8258, 12387, 16516, 20645, 24774, 28903, 33032, 37161, 41290, 45419, 49548, 53677, 57806, 61935, 19 | 4657, 528, 12915, 8786, 21173, 17044, 29431, 25302, 37689, 33560, 45947, 41818, 54205, 50076, 62463, 58334, 20 | 9314, 13379, 1056, 5121, 25830, 29895, 17572, 21637, 42346, 46411, 34088, 38153, 58862, 62927, 50604, 54669, 21 | 13907, 9842, 5649, 1584, 30423, 26358, 22165, 18100, 46939, 42874, 38681, 34616, 63455, 59390, 55197, 51132, 22 | 18628, 22757, 26758, 30887, 2112, 6241, 10242, 14371, 51660, 55789, 59790, 63919, 35144, 39273, 43274, 23 | 47403, 23285, 19156, 31415, 27286, 6769, 2640, 14899, 10770, 56317, 52188, 64447, 60318, 39801, 35672, 24 | 47931, 43802, 27814, 31879, 19684, 23749, 11298, 15363, 3168, 7233, 60846, 64911, 52716, 56781, 44330, 25 | 48395, 36200, 40265, 32407, 28342, 24277, 20212, 15891, 11826, 7761, 3696, 65439, 61374, 57309, 53244, 26 | 48923, 44858, 40793, 36728, 37256, 33193, 45514, 41451, 53516, 49453, 61774, 57711, 4224, 161, 12482, 8419, 27 | 20484, 16421, 28742, 24679, 33721, 37784, 41979, 46042, 49981, 54044, 58239, 62302, 689, 4752, 8947, 13010, 28 | 16949, 21012, 25207, 29270, 46570, 42443, 38312, 34185, 62830, 58703, 54572, 50445, 13538, 9411, 5280, 1153, 29 | 29798, 25671, 21540, 17413, 42971, 47098, 34713, 38840, 59231, 63358, 50973, 55100, 9939, 14066, 1681, 5808, 30 | 26199, 30326, 17941, 22068, 55628, 51565, 63758, 59695, 39368, 35305, 47498, 43435, 22596, 18533, 30726, 31 | 26663, 6336, 2273, 14466, 10403, 52093, 56156, 60223, 64286, 35833, 39896, 43963, 48026, 19061, 23124, 32 | 27191, 31254, 2801, 6864, 10931, 14994, 64814, 60687, 56684, 52557, 48554, 44427, 40424, 36297, 31782, 33 | 27655, 23652, 19525, 15522, 11395, 7392, 3265, 61215, 65342, 53085, 57212, 44955, 49082, 36825, 40952, 34 | 28183, 32310, 20053, 24180, 11923, 16050, 3793, 7920 35 | }; 36 | 37 | public int GetCRC16(byte[] bytes, int s, int e) 38 | { 39 | int crc = 0; 40 | 41 | for (int i = s; i < e; ++i) 42 | { 43 | crc = crc << 8 ^ LOOKUP_TABLE[(crc >> 8 ^ bytes[i] & 255) & 255]; 44 | } 45 | 46 | return crc & '\uffff'; 47 | } 48 | 49 | public int GetSlot(string key) 50 | { 51 | return RedisClient.ClusterAdapter.GetClusterSlot(key); 52 | } 53 | 54 | public int GetCRC16(byte[] bytes) 55 | { 56 | return GetCRC16(bytes, 0, bytes.Length); 57 | } 58 | 59 | public int GetCRC16(string key) 60 | { 61 | byte[] bytesKey = Encoding.UTF8.GetBytes(key); 62 | return GetCRC16(bytesKey, 0, bytesKey.Length); 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /src/FreeRedis/RedisClient/Modules/DelayQueue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | 6 | namespace FreeRedis 7 | { 8 | partial class RedisClient 9 | { 10 | /// 11 | /// 延时队列 12 | /// 13 | /// 延时队列Key 14 | /// 15 | public DelayQueue DelayQueue(string queueKey) => new DelayQueue(this, queueKey); 16 | } 17 | 18 | /// 19 | /// 延时队列 20 | /// 21 | public class DelayQueue 22 | { 23 | private readonly RedisClient _redisClient = null; 24 | 25 | private readonly string _queueKey; 26 | 27 | 28 | public DelayQueue(RedisClient redisClient, string queueKey) 29 | { 30 | _redisClient = redisClient; 31 | _queueKey = queueKey; 32 | } 33 | 34 | 35 | /// 36 | /// 写入延时队列 37 | /// 38 | /// 队列值:值不可重复 39 | /// 延迟执行时间 40 | /// 41 | public bool Enqueue(string value, TimeSpan delay) 42 | { 43 | var time = DateTime.UtcNow.Add(delay); 44 | long timestamp = (time.Ticks - new DateTime(1970, 1, 1).Ticks) / TimeSpan.TicksPerMillisecond; 45 | 46 | var res = _redisClient.ZAdd(_queueKey, timestamp, value); 47 | return res > 0; 48 | } 49 | 50 | /// 51 | /// 写入延时队列 52 | /// 53 | /// 队列值:值不可重复 54 | /// 延迟执行时间 55 | /// 56 | public bool Enqueue(string value, DateTime delay) 57 | { 58 | var time = TimeZoneInfo.ConvertTimeToUtc(delay); 59 | long timestamp = (time.Ticks - new DateTime(1970, 1, 1).Ticks) / TimeSpan.TicksPerMillisecond; 60 | var res = _redisClient.ZAdd(_queueKey, timestamp, value); 61 | return res > 0; 62 | } 63 | 64 | /// 65 | /// 消费延时队列,多个消费端不会重复 66 | /// 67 | /// 消费委托 68 | /// 轮询队列时长,默认400毫秒,值越小越准确 69 | public void Dequeue(Action action, int choke = 400, CancellationToken? token = null) 70 | { 71 | Thread thread = new Thread(() => 72 | { 73 | while (true) 74 | { 75 | try 76 | { 77 | if (token != null && token.Value.IsCancellationRequested) 78 | break; 79 | 80 | //阻塞节省CPU 81 | Thread.Sleep(choke); 82 | var res = InternalDequeue(); 83 | if (!string.IsNullOrWhiteSpace(res)) 84 | action.Invoke(res); 85 | } 86 | catch 87 | { 88 | // ignored 89 | } 90 | } 91 | }); 92 | 93 | thread.Start(); 94 | } 95 | 96 | #if isasync 97 | 98 | /// 99 | /// 消费延时队列,多个消费端不会重复 100 | /// 101 | /// 消费委托 102 | /// 轮询队列时长,默认400毫秒,值越小越准确 103 | /// 104 | public Task DequeueAsync(Func action, int choke = 400, CancellationToken? token = null) 105 | { 106 | return Task.Factory.StartNew(async () => 107 | { 108 | while (true) 109 | { 110 | try 111 | { 112 | if (token != null && token.Value.IsCancellationRequested) 113 | break; 114 | 115 | //阻塞节省CPU 116 | await Task.Delay(choke); 117 | var res = InternalDequeue(); 118 | if (!string.IsNullOrWhiteSpace(res)) 119 | await action.Invoke(res); 120 | } 121 | catch 122 | { 123 | // ignored 124 | } 125 | } 126 | }, TaskCreationOptions.LongRunning); 127 | } 128 | 129 | #endif 130 | 131 | //取队列任务 132 | private string InternalDequeue() 133 | { 134 | long timestamp = (DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1).Ticks) / TimeSpan.TicksPerMillisecond; 135 | 136 | //lua脚本保持原子性 137 | var script = @" 138 | local zrange = redis.call('zrangebyscore',KEYS[1],0,ARGV[1],'LIMIT',0,1) 139 | if next(zrange) ~= nil and #zrange > 0 then 140 | local rmnum = redis.call('zrem',KEYS[1],unpack(zrange)) 141 | if(rmnum > 0) then 142 | return zrange 143 | end 144 | else 145 | return {} 146 | end"; 147 | 148 | if (_redisClient.Eval(script, new[] { _queueKey }, timestamp) is object[] eval && eval.Any()) 149 | { 150 | var item = eval[0].ToString() ?? string.Empty; 151 | return item; 152 | } 153 | 154 | return default; 155 | } 156 | } 157 | } -------------------------------------------------------------------------------- /src/FreeRedis/RedisClient/Modules/RedisBloomCountMinSketch.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace FreeRedis 8 | { 9 | partial class RedisClient 10 | { 11 | #if isasync 12 | #region async (copy from sync) 13 | 14 | public Task CmsInitByDimAsync(string key, long width, long depth) => CallAsync("CMS.INITBYDIM".InputKey(key, width, depth), rt => rt.ThrowOrValue()); 15 | public Task CmsInitByProbAsync(string key, decimal error, decimal probability) => CallAsync("CMS.INITBYPROB".InputKey(key, error, probability), rt => rt.ThrowOrValue()); 16 | 17 | public Task CmsIncrByAsync(string key, string item, long increment) => CallAsync("CMS.INCRBY".InputKey(key, item, increment), rt => rt.ThrowOrValue(a => a.ConvertTo().FirstOrDefault())); 18 | public Task CmsIncrByAsync(string key, Dictionary itemIncrements) => CallAsync("CMS.INCRBY".InputKey(key).InputKv(itemIncrements, false, SerializeRedisValue), rt => rt.ThrowOrValue()); 19 | 20 | public Task CmsQueryAsync(string key, string[] items) => CallAsync("CMS.QUERY".InputKey(key, items), rt => rt.ThrowOrValue()); 21 | public Task CmsMergeAsync(string dest, long numKeys, string[] src, long[] weights) => CallAsync("CMS.MERGE" 22 | .InputKey(dest, numKeys) 23 | .InputKey(src) 24 | .InputIf(weights?.Any() == true, "WEIGHTS", weights), rt => rt.ThrowOrValue()); 25 | 26 | public Task> CmsInfoAsync(string key) => CallAsync("CMS.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash(rt.Encoding))); 27 | 28 | #endregion 29 | #endif 30 | 31 | public string CmsInitByDim(string key, long width, long depth) => Call("CMS.INITBYDIM".InputKey(key, width, depth), rt => rt.ThrowOrValue()); 32 | public string CmsInitByProb(string key, decimal error, decimal probability) => Call("CMS.INITBYPROB".InputKey(key, error, probability), rt => rt.ThrowOrValue()); 33 | 34 | public long CmsIncrBy(string key, string item, long increment) => Call("CMS.INCRBY".InputKey(key, item, increment), rt => rt.ThrowOrValue(a => a.ConvertTo().FirstOrDefault())); 35 | public long[] CmsIncrBy(string key, Dictionary itemIncrements) => Call("CMS.INCRBY".InputKey(key).InputKv(itemIncrements, false, SerializeRedisValue), rt => rt.ThrowOrValue()); 36 | 37 | public long[] CmsQuery(string key, string[] items) => Call("CMS.QUERY".InputKey(key, items), rt => rt.ThrowOrValue()); 38 | public string CmsMerge(string dest, long numKeys, string[] src, long[] weights) => Call("CMS.MERGE" 39 | .InputKey(dest, numKeys) 40 | .InputKey(src) 41 | .InputIf(weights?.Any() == true, "WEIGHTS", weights), rt => rt.ThrowOrValue()); 42 | 43 | public Dictionary CmsInfo(string key) => Call("CMS.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash(rt.Encoding))); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/FreeRedis/RedisClient/Modules/RedisBloomCuckooFilter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace FreeRedis 8 | { 9 | partial class RedisClient 10 | { 11 | #if isasync 12 | #region async (copy from sync) 13 | 14 | public Task CfReserveAsync(string key, long capacity, long? bucketSize = null, long? maxIterations = null, int? expansion = null) => CallAsync("CF.RESERVE" 15 | .InputKey(key, capacity) 16 | .InputIf(bucketSize != 2, "BUCKETSIZE", bucketSize) 17 | .InputIf(maxIterations != 2, "MAXITERATIONS", maxIterations) 18 | .InputIf(expansion != 2, "EXPANSION", expansion), rt => rt.ThrowOrValue()); 19 | 20 | public Task CfAddAsync(string key, string item) => CallAsync("CF.ADD".InputKey(key, item), rt => rt.ThrowOrValue()); 21 | public Task CfAddNxAsync(string key, string item) => CallAsync("CF.ADDNX".InputKey(key, item), rt => rt.ThrowOrValue()); 22 | 23 | async public Task CfInsertAsync(string key, string[] items, long? capacity = null, bool noCreate = false) => await CfInsertAsync(false, key, items, capacity, noCreate); 24 | async public Task CfInsertNxAsync(string key, string[] items, long? capacity = null, bool noCreate = false) => await CfInsertAsync(true, key, items, capacity, noCreate); 25 | Task CfInsertAsync(bool nx, string key, string[] items, long? capacity = null, bool noCreate = false) => CallAsync((nx ? "CF.INSERTNX" : "CF.INSERT") 26 | .InputKey(key) 27 | .InputIf(capacity != null, "CAPACITY", capacity) 28 | .InputIf(noCreate, "NOCREATE") 29 | .Input("ITEMS", items), rt => rt.ThrowOrValue()); 30 | 31 | public Task CfExistsAsync(string key, string item) => CallAsync("CF.EXISTS".InputKey(key, item), rt => rt.ThrowOrValue()); 32 | public Task CfDelAsync(string key, string item) => CallAsync("CF.DEL".InputKey(key, item), rt => rt.ThrowOrValue()); 33 | 34 | public Task CfCountAsync(string key, string item) => CallAsync("CF.COUNT".InputKey(key, item), rt => rt.ThrowOrValue()); 35 | 36 | public Task> CfScanDumpAsync(string key, long iter) => CallAsync("CF.SCANDUMP".InputKey(key, iter), rt => rt.ThrowOrValue((a, _) => 37 | new ScanResult(a[0].ConvertTo(), a[1].ConvertTo()))); 38 | 39 | public Task CfLoadChunkAsync(string key, long iter, byte[] data) => CallAsync("CF.LOADCHUNK".InputKey(key, iter).InputRaw(data), rt => rt.ThrowOrValue()); 40 | public Task> CfInfoAsync(string key) => CallAsync("CF.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash(rt.Encoding))); 41 | 42 | #endregion 43 | #endif 44 | 45 | public string CfReserve(string key, long capacity, long? bucketSize = null, long? maxIterations = null, int? expansion = null) => Call("CF.RESERVE" 46 | .InputKey(key, capacity) 47 | .InputIf(bucketSize != 2, "BUCKETSIZE", bucketSize) 48 | .InputIf(maxIterations != 2, "MAXITERATIONS", maxIterations) 49 | .InputIf(expansion != 2, "EXPANSION", expansion), rt => rt.ThrowOrValue()); 50 | 51 | public bool CfAdd(string key, string item) => Call("CF.ADD".InputKey(key, item), rt => rt.ThrowOrValue()); 52 | public bool CfAddNx(string key, string item) => Call("CF.ADDNX".InputKey(key, item), rt => rt.ThrowOrValue()); 53 | 54 | public string CfInsert(string key, string[] items, long? capacity = null, bool noCreate = false) => CfInsert(false, key, items, capacity, noCreate); 55 | public string CfInsertNx(string key, string[] items, long? capacity = null, bool noCreate = false) => CfInsert(true, key, items, capacity, noCreate); 56 | string CfInsert(bool nx, string key, string[] items, long? capacity = null, bool noCreate = false) => Call((nx ? "CF.INSERTNX" : "CF.INSERT") 57 | .InputKey(key) 58 | .InputIf(capacity != null, "CAPACITY", capacity) 59 | .InputIf(noCreate, "NOCREATE") 60 | .Input("ITEMS", items), rt => rt.ThrowOrValue()); 61 | 62 | public bool CfExists(string key, string item) => Call("CF.EXISTS".InputKey(key, item), rt => rt.ThrowOrValue()); 63 | public bool CfDel(string key, string item) => Call("CF.DEL".InputKey(key, item), rt => rt.ThrowOrValue()); 64 | 65 | public long CfCount(string key, string item) => Call("CF.COUNT".InputKey(key, item), rt => rt.ThrowOrValue()); 66 | 67 | public ScanResult CfScanDump(string key, long iter) => Call("CF.SCANDUMP".InputKey(key, iter), rt => rt.ThrowOrValue((a, _) => 68 | new ScanResult(a[0].ConvertTo(), a[1].ConvertTo()))); 69 | 70 | public string CfLoadChunk(string key, long iter, byte[] data) => Call("CF.LOADCHUNK".InputKey(key, iter).InputRaw(data), rt => rt.ThrowOrValue()); 71 | public Dictionary CfInfo(string key) => Call("CF.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash(rt.Encoding))); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/FreeRedis/RedisClient/Modules/RedisBloomTopKFilter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace FreeRedis 8 | { 9 | partial class RedisClient 10 | { 11 | #if isasync 12 | #region async (copy from sync) 13 | 14 | public Task TopkReserveAsync(string key, long topk, long width, long depth, decimal decay) => CallAsync("TOPK.RESERVE".InputKey(key).Input(topk, width, depth, decay), rt => rt.ThrowOrValue()); 15 | public Task TopkAddAsync(string key, string[] items) => CallAsync("TOPK.ADD".InputKey(key, items), rt => rt.ThrowOrValue()); 16 | 17 | public Task TopkIncrByAsync(string key, string item, long increment) => CallAsync("TOPK.INCRBY".InputKey(key, item, increment), rt => rt.ThrowOrValue((a, _) => a.FirstOrDefault().ConvertTo())); 18 | public Task TopkIncrByAsync(string key, Dictionary itemIncrements) => CallAsync("TOPK.INCRBY".InputKey(key).InputKv(itemIncrements, false, SerializeRedisValue), rt => rt.ThrowOrValue()); 19 | 20 | public Task TopkQueryAsync(string key, string[] items) => CallAsync("TOPK.QUERY".InputKey(key, items), rt => rt.ThrowOrValue()); 21 | public Task TopkCountAsync(string key, string[] items) => CallAsync("TOPK.COUNT".InputKey(key, items), rt => rt.ThrowOrValue()); 22 | 23 | public Task TopkListAsync(string key) => CallAsync("TOPK.LIST".InputKey(key), rt => rt.ThrowOrValue()); 24 | public Task> TopkInfoAsync(string key) => CallAsync("TOPK.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash(rt.Encoding))); 25 | 26 | #endregion 27 | #endif 28 | 29 | public string TopkReserve(string key, long topk, long width, long depth, decimal decay) => Call("TOPK.RESERVE".InputKey(key).Input(topk, width, depth, decay), rt => rt.ThrowOrValue()); 30 | public string[] TopkAdd(string key, string[] items) => Call("TOPK.ADD".InputKey(key, items), rt => rt.ThrowOrValue()); 31 | 32 | public string TopkIncrBy(string key, string item, long increment) => Call("TOPK.INCRBY".InputKey(key, item, increment), rt => rt.ThrowOrValue((a, _) => a.FirstOrDefault().ConvertTo())); 33 | public string[] TopkIncrBy(string key, Dictionary itemIncrements) => Call("TOPK.INCRBY".InputKey(key).InputKv(itemIncrements, false, SerializeRedisValue), rt => rt.ThrowOrValue()); 34 | 35 | public bool[] TopkQuery(string key, string[] items) => Call("TOPK.QUERY".InputKey(key, items), rt => rt.ThrowOrValue()); 36 | public long[] TopkCount(string key, string[] items) => Call("TOPK.COUNT".InputKey(key, items), rt => rt.ThrowOrValue()); 37 | 38 | public string[] TopkList(string key) => Call("TOPK.LIST".InputKey(key), rt => rt.ThrowOrValue()); 39 | public Dictionary TopkInfo(string key) => Call("TOPK.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash(rt.Encoding))); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/FreeRedis/RedisClient/Modules/SubscribeStream.cs: -------------------------------------------------------------------------------- 1 | using FreeRedis.Internal; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Collections.Concurrent; 5 | using System.Linq; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using System.Text; 9 | using FreeRedis.Internal.ObjectPool; 10 | 11 | namespace FreeRedis 12 | { 13 | partial class RedisClient 14 | { 15 | public SubscribeStreamObject SubscribeStream(string streamKey, Action> onMessage) 16 | { 17 | if (string.IsNullOrEmpty(streamKey)) throw new ArgumentException("Parameter streamKey cannot be empty"); 18 | var redis = this; 19 | var subobj = new SubscribeStreamObject(); 20 | 21 | var groupName = "FreeRedis__group"; 22 | var consumerName = "FreeRedis__consumer"; 23 | void CreateGroupAndConsumer() 24 | { 25 | using (var loc1 = redis.StartPipe()) 26 | { 27 | loc1.XGroupCreate(streamKey, groupName, "$", true); 28 | loc1.XGroupCreateConsumer(streamKey, groupName, consumerName); 29 | loc1.EndPipe(); 30 | } 31 | } 32 | 33 | if (redis.Exists(streamKey) == false) CreateGroupAndConsumer(); 34 | else 35 | { 36 | if (redis.Type(streamKey) != KeyType.stream) throw new ArgumentException($"'{streamKey}' type is not STREAM"); 37 | if (redis.XInfoGroups(streamKey).Any(a => a.name == groupName) == false) CreateGroupAndConsumer(); 38 | else if (redis.XInfoConsumers(streamKey, groupName).Any(a => a.name == consumerName) == false) redis.XGroupCreateConsumer(streamKey, groupName, consumerName); 39 | } 40 | 41 | TestTrace.WriteLine($"Subscribing to stream(streamKey:{streamKey})", ConsoleColor.DarkGreen); 42 | new Thread(() => 43 | { 44 | while (subobj.IsUnsubscribed == false) 45 | { 46 | try 47 | { 48 | //var result = redis.XReadGroup(groupName, consumerName, 5000, streamKey, ">"); 49 | var result = Call("XREADGROUP" 50 | .Input("GROUP", groupName, consumerName) 51 | .Input("COUNT", 1) 52 | .Input("BLOCK", 5000) 53 | .InputRaw("STREAMS") 54 | .InputKey(streamKey) 55 | .Input(">"), rt => 56 | { 57 | if (rt.IsError) 58 | { 59 | if ( 60 | rt.SimpleError == $"UNBLOCKED the stream key no longer exists" || 61 | rt.SimpleError == $"NOGROUP No such key '{streamKey}' or consumer group '{groupName}' in XREADGROUP with GROUP option") 62 | { 63 | CreateGroupAndConsumer(); 64 | return null; 65 | } 66 | } 67 | return rt.ThrowOrValueToXRead(); 68 | })?.FirstOrDefault()?.entries?.FirstOrDefault(); 69 | if (result != null) 70 | { 71 | onMessage?.Invoke(result.fieldValues?.MapToHash(Encoding.UTF8)); 72 | redis.XAck(streamKey, groupName, result.id); 73 | } 74 | } 75 | catch (ObjectDisposedException) 76 | { 77 | } 78 | catch (Exception ex) 79 | { 80 | TestTrace.WriteLine($"Stream subscription error(streamKey:{streamKey}): {ex.Message}", ConsoleColor.DarkRed); 81 | 82 | Thread.CurrentThread.Join(3000); 83 | } 84 | } 85 | }).Start(); 86 | 87 | AppDomain.CurrentDomain.ProcessExit += (s1, e1) => 88 | { 89 | subobj.Dispose(); 90 | }; 91 | try 92 | { 93 | Console.CancelKeyPress += (s1, e1) => 94 | { 95 | if (e1.Cancel) return; 96 | subobj.Dispose(); 97 | }; 98 | } 99 | catch { } 100 | 101 | return subobj; 102 | } 103 | } 104 | } 105 | 106 | namespace FreeRedis.Internal 107 | { 108 | public class SubscribeStreamObject : IDisposable 109 | { 110 | internal List OtherSubs = new List(); 111 | public bool IsUnsubscribed { get; set; } 112 | 113 | public void Dispose() 114 | { 115 | this.IsUnsubscribed = true; 116 | foreach (var sub in OtherSubs) sub.Dispose(); 117 | } 118 | } 119 | } -------------------------------------------------------------------------------- /src/FreeRedis/RedisClient/SPubSub.cs: -------------------------------------------------------------------------------- 1 | //using FreeRedis.Internal; 2 | //using System; 3 | //using System.Collections.Generic; 4 | //using System.Collections.Concurrent; 5 | //using System.Linq; 6 | //using System.Threading; 7 | //using System.Threading.Tasks; 8 | 9 | //namespace FreeRedis 10 | //{ 11 | // partial class RedisClient 12 | // { 13 | 14 | //#if isasync 15 | // #region async (copy from sync) 16 | // /// 17 | // /// redis 7.0 shard pub/sub 18 | // /// 19 | // public Task SPublishAsync(string shardchannel, string message) => CallAsync("SPUBLISH".InputKey(shardchannel).Input(message), rt => rt.ThrowOrValue()); 20 | // public Task PubSubShardChannelsAsync(string pattern = "*") => CallAsync("PUBSUB".SubCommand("SHARDCHANNELS").Input(pattern), rt => rt.ThrowOrValue()); 21 | // public Task PubSubShardNumSubAsync(string channel) => CallAsync("PUBSUB".SubCommand("SHARDNUMSUB").InputKey(channel), rt => rt.ThrowOrValue((a, _) => a.MapToList((x, y) => y.ConvertTo()).FirstOrDefault())); 22 | // public Task PubSubShardNumSubAsync(string[] channels) => CallAsync("PUBSUB".SubCommand("SHARDNUMSUB").InputKey(channels), rt => rt.ThrowOrValue((a, _) => a.MapToList((x, y) => y.ConvertTo()).ToArray())); 23 | // #endregion 24 | //#endif 25 | 26 | // /// 27 | // /// redis 7.0 shard pub/sub 28 | // /// 29 | // public long SPublish(string shardchannel, string message) => Call("SPUBLISH".InputKey(shardchannel).Input(message), rt => rt.ThrowOrValue()); 30 | // public string[] PubSubShardChannels(string pattern = "*") => Call("PUBSUB".SubCommand("SHARDCHANNELS").Input(pattern), rt => rt.ThrowOrValue()); 31 | // public long PubSubShardNumSub(string channel) => Call("PUBSUB".SubCommand("SHARDNUMSUB").InputKey(channel), rt => rt.ThrowOrValue((a, _) => a.MapToList((x, y) => y.ConvertTo()).FirstOrDefault())); 32 | // public long[] PubSubShardNumSub(string[] channels) => Call("PUBSUB".SubCommand("SHARDNUMSUB").InputKey(channels), rt => rt.ThrowOrValue((a, _) => a.MapToList((x, y) => y.ConvertTo()).ToArray())); 33 | 34 | // /// 35 | // /// redis 7.0 shard pub/sub 36 | // /// 37 | // public IDisposable SSubscribe(string shardchannel, Action handler) 38 | // { 39 | // if (string.IsNullOrEmpty(shardchannel)) throw new ArgumentNullException(nameof(shardchannel)); 40 | // if (handler == null) throw new ArgumentNullException(nameof(handler)); 41 | 42 | // return _pubsub.Subscribe(false, true, new[] { shardchannel }, (p, k, d) => handler(k, d)); 43 | // } 44 | // /// 45 | // /// redis 7.0 shard pub/sub 46 | // /// 47 | // public void SUnSubscribe(string shardchannel) => _pubsub.UnSubscribe(false, true, new[] { shardchannel }); 48 | // } 49 | //} -------------------------------------------------------------------------------- /src/FreeRedis/RedisClient/Scripting.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace FreeRedis 8 | { 9 | partial class RedisClient 10 | { 11 | #if isasync 12 | #region async (copy from sync) 13 | public Task EvalAsync(string script, string[] keys = null, params object[] arguments) => CallAsync("EVAL" 14 | .Input(script, keys?.Length ?? 0) 15 | .InputKeyIf(keys?.Any() == true, keys) 16 | .Input(arguments), rt => rt.ThrowOrValue()); 17 | 18 | public Task EvalShaAsync(string sha1, string[] keys = null, params object[] arguments) => CallAsync("EVALSHA" 19 | .Input(sha1, keys?.Length ?? 0) 20 | .InputKeyIf(keys?.Any() == true, keys) 21 | .Input(arguments), rt => rt.ThrowOrValue()); 22 | 23 | public Task ScriptExistsAsync(string sha1) => CallAsync("SCRIPT".SubCommand("EXISTS").InputRaw(sha1), rt => rt.ThrowOrValue((a, _) => a.FirstOrDefault().ConvertTo())); 24 | public Task ScriptExistsAsync(string[] sha1) => CallAsync("SCRIPT".SubCommand("EXISTS").Input(sha1), rt => rt.ThrowOrValue()); 25 | 26 | public Task ScriptFlushAsync() => CallAsync("SCRIPT".SubCommand("FLUSH"), rt => rt.ThrowOrNothing()); 27 | public Task ScriptKillAsync() => CallAsync("SCRIPT".SubCommand("KILL"), rt => rt.ThrowOrNothing()); 28 | public Task ScriptLoadAsync(string script) => CallAsync("SCRIPT".SubCommand("LOAD").InputRaw(script), rt => rt.ThrowOrValue()); 29 | #endregion 30 | #endif 31 | 32 | public object Eval(string script, string[] keys = null, params object[] arguments) => Call("EVAL" 33 | .Input(script, keys?.Length ?? 0) 34 | .InputKeyIf(keys?.Any() == true, keys) 35 | .Input(arguments), rt => rt.ThrowOrValue()); 36 | 37 | public object EvalSha(string sha1, string[] keys = null, params object[] arguments) => Call("EVALSHA" 38 | .Input(sha1, keys?.Length ?? 0) 39 | .InputKeyIf(keys?.Any() == true, keys) 40 | .Input(arguments), rt => rt.ThrowOrValue()); 41 | 42 | public bool ScriptExists(string sha1) => Call("SCRIPT".SubCommand("EXISTS").InputRaw(sha1), rt => rt.ThrowOrValue((a, _) => a.FirstOrDefault().ConvertTo())); 43 | public bool[] ScriptExists(string[] sha1) => Call("SCRIPT".SubCommand("EXISTS").Input(sha1), rt => rt.ThrowOrValue()); 44 | 45 | public void ScriptFlush() => Call("SCRIPT".SubCommand("FLUSH"), rt => rt.ThrowOrNothing()); 46 | public void ScriptKill() => Call("SCRIPT".SubCommand("KILL"), rt => rt.ThrowOrNothing()); 47 | public string ScriptLoad(string script) => Call("SCRIPT".SubCommand("LOAD").InputRaw(script), rt => rt.ThrowOrValue()); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/FreeRedis/RedisClientAsync.cs: -------------------------------------------------------------------------------- 1 | #if isasync 2 | using FreeRedis.Internal; 3 | using FreeRedis.Internal.ObjectPool; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Collections.Concurrent; 7 | using System.IO; 8 | using System.Linq; 9 | using System.Text; 10 | using System.Threading; 11 | using System.Diagnostics; 12 | using System.Collections; 13 | using System.Threading.Tasks; 14 | 15 | namespace FreeRedis 16 | { 17 | partial class RedisClient 18 | { 19 | public Task CallAsync(CommandPacket cmd) => Adapter.AdapterCallAsync(cmd, rt => rt.ThrowOrValue()); 20 | public Task CallAsync(CommandPacket cmd, Func parse) => Adapter.AdapterCallAsync(cmd, parse); 21 | 22 | async internal Task LogCallAsync(CommandPacket cmd, Func> func) 23 | { 24 | cmd.Prefix(Prefix); 25 | var isnotice = this.Notice != null; 26 | if (isnotice == false && this.Interceptors.Any() == false) return await func(); 27 | Exception exception = null; 28 | 29 | T ret = default(T); 30 | var isaopval = false; 31 | IInterceptor[] aops = new IInterceptor[this.Interceptors.Count + (isnotice ? 1 : 0)]; 32 | Stopwatch[] aopsws = new Stopwatch[aops.Length]; 33 | for (var idx = 0; idx < aops.Length; idx++) 34 | { 35 | aopsws[idx] = new Stopwatch(); 36 | aopsws[idx].Start(); 37 | aops[idx] = isnotice && idx == aops.Length - 1 ? new NoticeCallInterceptor(this) : this.Interceptors[idx]?.Invoke(); 38 | var args = new InterceptorBeforeEventArgs(this, cmd, typeof(T)); 39 | aops[idx].Before(args); 40 | if (args.ValueIsChanged && args.Value is T argsValue) 41 | { 42 | isaopval = true; 43 | ret = argsValue; 44 | } 45 | } 46 | try 47 | { 48 | if (isaopval == false) ret = await func(); 49 | return ret; 50 | } 51 | catch (Exception ex) 52 | { 53 | exception = ex; 54 | throw; 55 | } 56 | finally 57 | { 58 | for (var idx = 0; idx < aops.Length; idx++) 59 | { 60 | aopsws[idx].Stop(); 61 | var args = new InterceptorAfterEventArgs(this, cmd, typeof(T), ret, exception, aopsws[idx].ElapsedMilliseconds); 62 | aops[idx].After(args); 63 | } 64 | } 65 | } 66 | } 67 | } 68 | #endif -------------------------------------------------------------------------------- /src/FreeRedis/key.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2881099/FreeRedis/cc5bdb638a1035cc64b9bdc2778a2875cf46b1d9/src/FreeRedis/key.snk -------------------------------------------------------------------------------- /test/Benchmark/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2881099/FreeRedis/cc5bdb638a1035cc64b9bdc2778a2875cf46b1d9/test/Benchmark/README.md -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/CommandFlagsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Xunit; 6 | 7 | namespace FreeRedis.Tests 8 | { 9 | public class CommandFlagsTests : TestBase 10 | { 11 | [Fact] 12 | public void Test01() 13 | { 14 | var methodsCount = typeof(RedisClient).GetMethods().Count(); 15 | } 16 | 17 | [Fact] 18 | public void Command() 19 | { 20 | string UFString(string text) 21 | { 22 | if (text.Length <= 1) return text.ToUpper(); 23 | else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1); 24 | } 25 | 26 | var rt = cli.Command(); 27 | //var rt = cli.CommandInfo("mset", "mget", "set", "get", "rename"); 28 | var flags = new List(); 29 | var flags7 = new List(); 30 | var diccmd = new Dictionary(); 31 | 32 | var sb = string.Join("\r\n\r\n", (rt).OrderBy(a1 => (a1 as object[])[0].ToString()).Select(a1 => 33 | { 34 | var a = a1 as object[]; 35 | var cmd = a[0].ToString(); 36 | var plen = int.Parse(a[1].ToString()); 37 | var firstKey = int.Parse(a[3].ToString()); 38 | var lastKey = int.Parse(a[4].ToString()); 39 | var stepCount = int.Parse(a[5].ToString()); 40 | 41 | var aflags = (a[2] as object[]).Select(a => a.ToString()).ToArray(); 42 | var fopts = (a[6] as object[]).Select(a => a.ToString()).ToArray(); 43 | flags.AddRange(aflags); 44 | flags7.AddRange(fopts); 45 | 46 | diccmd.Add(cmd.ToUpper(), (aflags, fopts)); 47 | 48 | var parms = ""; 49 | if (plen > 1) 50 | { 51 | for (var x = 1; x < plen; x++) 52 | { 53 | if (x == firstKey) parms += "string key, "; 54 | else parms += $"string arg{x}, "; 55 | } 56 | parms = parms.Remove(parms.Length - 2); 57 | } 58 | if (plen < 0) 59 | { 60 | for (var x = 1; x < -plen; x++) 61 | { 62 | if (x == firstKey) 63 | { 64 | if (firstKey != lastKey) parms += "string[] keys, "; 65 | else parms += "string key, "; 66 | } 67 | else 68 | { 69 | if (firstKey != lastKey) parms += $"string[] arg{x}, "; 70 | else parms += $"string arg{x}, "; 71 | } 72 | } 73 | if (parms.Length > 0) 74 | parms = parms.Remove(parms.Length - 2); 75 | } 76 | 77 | return $@" 78 | //{string.Join(", ", a[2] as object[])} 79 | //{string.Join(", ", a[6] as object[])} 80 | public void {UFString(cmd)}({parms}) {{ }}"; 81 | })); 82 | flags = flags.Distinct().ToList(); 83 | flags7 = flags7.Distinct().ToList(); 84 | 85 | 86 | var sboptions = new StringBuilder(); 87 | foreach (var cmd in CommandSets._allCommands) 88 | { 89 | if (diccmd.TryGetValue(cmd, out var tryv)) 90 | { 91 | sboptions.Append($@" 92 | [""{cmd}""] = new CommandSets("); 93 | 94 | for (var x = 0; x < tryv.Item1.Length; x++) 95 | { 96 | if (x > 0) sboptions.Append(" | "); 97 | sboptions.Append($"ServerFlag.{tryv.Item1[x].Replace("readonly", "@readonly")}"); 98 | } 99 | 100 | sboptions.Append(", "); 101 | for (var x = 0; x < tryv.Item2.Length; x++) 102 | { 103 | if (x > 0) sboptions.Append(" | "); 104 | sboptions.Append($"ServerTag.{tryv.Item2[x].TrimStart('@').Replace("string", "@string")}"); 105 | } 106 | 107 | sboptions.Append(", LocalStatus.none),"); 108 | } 109 | else 110 | { 111 | sboptions.Append($@" 112 | [""{cmd}""] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none), "); 113 | } 114 | } 115 | 116 | var optioncode = sboptions.ToString(); 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/CommandPacketTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Concurrent; 4 | using System.Text; 5 | using Xunit; 6 | 7 | namespace FreeRedis.Tests 8 | { 9 | public class CommandPacketTests 10 | { 11 | 12 | [Fact] 13 | public void Prefix() 14 | { 15 | var cmd1 = new CommandPacket("GET").InputKey("key1").Prefix("prefix_"); 16 | Assert.Equal("GET prefix_key1", cmd1.ToString()); 17 | Assert.Equal("GET prefix01_key1", cmd1.Prefix("prefix01_").ToString()); //replace 18 | 19 | var cmd2 = new CommandPacket("MGET").InputKey(new[] { "key1", "key2" }).Prefix("prefix_"); 20 | Assert.Equal("MGET prefix_key1 prefix_key2", cmd2.ToString()); 21 | Assert.Equal("MGET prefix01_key1 prefix01_key2", cmd2.Prefix("prefix01_").ToString()); //replace 22 | } 23 | 24 | [Fact] 25 | public void GetKey() 26 | { 27 | var cmd1 = new CommandPacket("GET").InputKey("key1").Prefix("prefix_"); 28 | Assert.Equal("prefix_key1", cmd1.GetKey(0)); 29 | Assert.Equal("key1", cmd1.GetKey(0, true)); 30 | Assert.Equal("prefix01_key1", cmd1.Prefix("prefix01_").GetKey(0)); //replace 31 | Assert.Equal("key1", cmd1.Prefix("prefix01_").GetKey(0, true)); //replace 32 | 33 | var cmd2 = new CommandPacket("MGET").InputKey(new[] { "key1", "key2" }).Prefix("prefix_"); 34 | Assert.Equal("prefix_key1", cmd2.GetKey(0)); 35 | Assert.Equal("key1", cmd2.GetKey(0, true)); 36 | Assert.Equal("prefix_key2", cmd2.GetKey(1)); 37 | Assert.Equal("key2", cmd2.GetKey(1, true)); 38 | Assert.Equal("prefix01_key1", cmd2.Prefix("prefix01_").GetKey(0)); //replace 39 | Assert.Equal("key1", cmd2.Prefix("prefix01_").GetKey(0, true)); //replace 40 | Assert.Equal("prefix01_key2", cmd2.Prefix("prefix01_").GetKey(1)); //replace 41 | Assert.Equal("key2", cmd2.Prefix("prefix01_").GetKey(1, true)); //replace 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/FreeRedis.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | all 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | 15 | 16 | all 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/InterceptorTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Concurrent; 4 | using System.Text; 5 | using Xunit; 6 | using FreeRedis.Internal; 7 | using System.Linq; 8 | 9 | namespace FreeRedis.Tests 10 | { 11 | public class InterceptorTests 12 | { 13 | public static RedisClient CreateClient() => new RedisClient(RedisEnvironmentHelper.GetHost("redis_interceptor")); 14 | 15 | [Fact] 16 | public void Interceptor() 17 | { 18 | using (var cli = CreateClient()) 19 | { 20 | cli.Interceptors.Add(() => new MemoryCacheAop()); 21 | 22 | cli.Set("Interceptor01", "123123"); 23 | 24 | var val1 = cli.Get("Interceptor01"); 25 | var val2 = cli.Get("Interceptor01"); 26 | var val3 = cli.Get("Interceptor01"); 27 | 28 | Assert.Equal("123123", val1); 29 | Assert.Equal("123123", val2); 30 | Assert.Equal("123123", val3); 31 | } 32 | } 33 | } 34 | 35 | class MemoryCacheAop : IInterceptor 36 | { 37 | static ConcurrentDictionary _dicStrings = new ConcurrentDictionary(); 38 | 39 | public void After(InterceptorAfterEventArgs args) 40 | { 41 | switch (args.Command._command) 42 | { 43 | case "GET": 44 | if (_iscached == false && args.Exception == null) 45 | _dicStrings.TryAdd(args.Command.GetKey(0), args.Value); 46 | break; 47 | } 48 | } 49 | 50 | bool _iscached = false; 51 | public void Before(InterceptorBeforeEventArgs args) 52 | { 53 | switch (args.Command._command) 54 | { 55 | case "GET": 56 | if (_dicStrings.TryGetValue(args.Command.GetKey(0), out var tryval)) 57 | { 58 | args.Value = tryval; 59 | _iscached = true; 60 | } 61 | break; 62 | } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/RedisClientTests/AdapterTests/PipelineTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using Xunit; 9 | 10 | namespace FreeRedis.Tests.RedisClientTests.Other 11 | { 12 | public class PipelineTests : TestBase 13 | { 14 | [Fact] 15 | public void StartPipe() 16 | { 17 | var key = Guid.NewGuid().ToString(); 18 | using (var pipe = cli.StartPipe()) 19 | { 20 | pipe.IncrBy(key, 10); 21 | 22 | pipe.Set("StartPipeTestSet_null", Null); 23 | pipe.Get("StartPipeTestSet_null"); 24 | 25 | pipe.Set("StartPipeTestSet_string", String); 26 | pipe.Get("StartPipeTestSet_string"); 27 | 28 | pipe.Set("StartPipeTestSet_bytes", Bytes); 29 | pipe.Get("StartPipeTestSet_bytes"); 30 | 31 | pipe.Set("StartPipeTestSet_class", Class); 32 | pipe.Get("StartPipeTestSet_class"); 33 | } 34 | 35 | using (var pipe = cli.StartPipe()) 36 | { 37 | pipe.IncrBy(key, 10); 38 | 39 | pipe.Set("StartPipeTestSet_null", Null); 40 | pipe.Get("StartPipeTestSet_null"); 41 | 42 | pipe.Set("StartPipeTestSet_string", String); 43 | pipe.Get("StartPipeTestSet_string"); 44 | 45 | pipe.Set("StartPipeTestSet_bytes", Bytes); 46 | pipe.Get("StartPipeTestSet_bytes"); 47 | 48 | pipe.Set("StartPipeTestSet_class", Class); 49 | pipe.Get("StartPipeTestSet_class"); 50 | 51 | var ret = pipe.EndPipe(); 52 | 53 | Assert.Equal(10L, ret[0]); 54 | Assert.Equal("", ret[2].ToString()); 55 | Assert.Equal(String, ret[4].ToString()); 56 | Assert.Equal(Bytes, ret[6]); 57 | Assert.Equal(Class.ToString(), ret[8].ToString()); 58 | } 59 | } 60 | 61 | //[Fact] 62 | //public void StartPipeAsync() 63 | //{ 64 | // var key = Guid.NewGuid().ToString(); 65 | // using (var pipe = cli.StartPipe()) 66 | // { 67 | // long t1 = 0; 68 | // pipe.IncrByAsync(key, 10); 69 | 70 | // pipe.SetAsync("StartPipeAsyncTestSet_null", Null); 71 | // string t3 = ""; 72 | // pipe.GetAsync("StartPipeAsyncTestSet_null"); 73 | 74 | // pipe.SetAsync("StartPipeAsyncTestSet_string", String); 75 | // string t4 = null; 76 | // pipe.GetAsync("StartPipeAsyncTestSet_string"); 77 | 78 | // pipe.SetAsync("StartPipeAsyncTestSet_bytes", Bytes); 79 | // byte[] t6 = null; 80 | // pipe.GetAsync("StartPipeAsyncTestSet_bytes"); 81 | 82 | // pipe.SetAsync("StartPipeAsyncTestSet_class", Class); 83 | // TestClass t8 = null; 84 | // pipe.GetAsync("StartPipeAsyncTestSet_class"); 85 | // } 86 | 87 | // using (var pipe = cli.StartPipe()) 88 | // { 89 | // var tasks = new List(); 90 | // long t1 = 0; 91 | // tasks.Add(pipe.IncrByAsync(key, 10).ContinueWith(t => t1 = t.Result)); 92 | 93 | // pipe.SetAsync("StartPipeAsyncTestSet_null", Null); 94 | // string t3 = ""; 95 | // tasks.Add(pipe.GetAsync("StartPipeAsyncTestSet_null").ContinueWith(t => t3 = t.Result)); 96 | 97 | // pipe.SetAsync("StartPipeAsyncTestSet_string", String); 98 | // string t4 = null; 99 | // tasks.Add(pipe.GetAsync("StartPipeAsyncTestSet_string").ContinueWith(t => t4 = t.Result)); 100 | 101 | // pipe.SetAsync("StartPipeAsyncTestSet_bytes", Bytes); 102 | // byte[] t6 = null; 103 | // tasks.Add(pipe.GetAsync("StartPipeAsyncTestSet_bytes").ContinueWith(t => t6 = t.Result)); 104 | 105 | // pipe.SetAsync("StartPipeAsyncTestSet_class", Class); 106 | // TestClass t8 = null; 107 | // tasks.Add(pipe.GetAsync("StartPipeAsyncTestSet_class").ContinueWith(t => t8 = t.Result)); 108 | 109 | // var ret = pipe.EndPipe(); 110 | // Task.WaitAll(tasks.ToArray()); 111 | 112 | // Assert.Equal(10L, ret[0]); 113 | // Assert.Equal("", ret[2].ToString()); 114 | // Assert.Equal(String, ret[4].ToString()); 115 | // Assert.Equal(Bytes, ret[6]); 116 | // Assert.Equal(Class.ToString(), ret[8].ToString()); 117 | 118 | // Assert.Equal(10L, t1); 119 | // Assert.Equal("", t3); 120 | // Assert.Equal(String, t4); 121 | // Assert.Equal(Bytes, t6); 122 | // Assert.Equal(Class.ToString(), t8.ToString()); 123 | // } 124 | //} 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/RedisClientTests/AdapterTests/TransactionTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using Xunit; 9 | 10 | namespace FreeRedis.Tests.RedisClientTests.Other 11 | { 12 | public class TransactionTests : TestBase 13 | { 14 | [Fact] 15 | public void Multi() 16 | { 17 | using (var tran = cli.Multi()) 18 | { 19 | tran.Discard(); 20 | } 21 | 22 | var key = Guid.NewGuid().ToString(); 23 | using (var tran = cli.Multi()) 24 | { 25 | tran.IncrBy(key, 10); 26 | 27 | tran.Set("MultiTestSet_null", Null); 28 | tran.Get("MultiTestSet_null"); 29 | 30 | tran.Set("MultiTestSet_string", String); 31 | tran.Get("MultiTestSet_string"); 32 | 33 | tran.Set("MultiTestSet_bytes", Bytes); 34 | tran.Get("MultiTestSet_bytes"); 35 | 36 | tran.Set("MultiTestSet_class", Class); 37 | tran.Get("MultiTestSet_class"); 38 | 39 | tran.Discard(); 40 | } 41 | 42 | using (var tran = cli.Multi()) 43 | { 44 | tran.IncrBy(key, 10); 45 | 46 | tran.Set("MultiTestSet_null", Null); 47 | tran.Get("MultiTestSet_null"); 48 | 49 | tran.Set("MultiTestSet_string", String); 50 | tran.Get("MultiTestSet_string"); 51 | 52 | tran.Set("MultiTestSet_bytes", Bytes); 53 | tran.Get("MultiTestSet_bytes"); 54 | 55 | tran.Set("MultiTestSet_class", Class); 56 | tran.Get("MultiTestSet_class"); 57 | 58 | var ret = tran.Exec(); 59 | 60 | Assert.Equal(10L, ret[0]); 61 | Assert.Equal("", ret[2].ToString()); 62 | Assert.Equal(String, ret[4].ToString()); 63 | Assert.Equal(Bytes, ret[6]); 64 | Assert.Equal(Class.ToString(), ret[8].ToString()); 65 | } 66 | } 67 | 68 | //[Fact] 69 | //public void MultiAsync() 70 | //{ 71 | // using (var tran = cli.Multi()) 72 | // { 73 | // tran.Discard(); 74 | // } 75 | 76 | // var key = Guid.NewGuid().ToString(); 77 | // using (var tran = cli.Multi()) 78 | // { 79 | // long t1 = 0; 80 | // tran.IncrByAsync(key, 10); 81 | 82 | // tran.SetAsync("MultiAsyncTestSet_null", Null); 83 | // string t3 = ""; 84 | // tran.GetAsync("MultiAsyncTestSet_null"); 85 | 86 | // tran.SetAsync("MultiAsyncTestSet_string", String); 87 | // string t4 = null; 88 | // tran.GetAsync("MultiAsyncTestSet_string"); 89 | 90 | // tran.SetAsync("MultiAsyncTestSet_bytes", Bytes); 91 | // byte[] t6 = null; 92 | // tran.GetAsync("TestSet_bytes"); 93 | 94 | // tran.SetAsync("MultiAsyncTestSet_class", Class); 95 | // TestClass t8 = null; 96 | // tran.GetAsync("MultiAsyncTestSet_class"); 97 | 98 | // tran.Discard(); 99 | // } 100 | 101 | // using (var tran = cli.Multi()) 102 | // { 103 | // var tasks = new List(); 104 | // long t1 = 0; 105 | // tasks.Add(tran.IncrByAsync(key, 10).ContinueWith(t => 106 | // t1 = t.Result)); 107 | 108 | // tran.SetAsync("MultiAsyncTestSet_null", Null); 109 | // string t3 = ""; 110 | // tasks.Add(tran.GetAsync("MultiAsyncTestSet_null").ContinueWith(t => t3 = t.Result)); 111 | 112 | // tran.SetAsync("MultiAsyncTestSet_string", String); 113 | // string t4 = null; 114 | // tasks.Add(tran.GetAsync("MultiAsyncTestSet_string").ContinueWith(t => t4 = t.Result)); 115 | 116 | // tran.SetAsync("MultiAsyncTestSet_bytes", Bytes); 117 | // byte[] t6 = null; 118 | // tasks.Add(tran.GetAsync("MultiAsyncTestSet_bytes").ContinueWith(t => t6 = t.Result)); 119 | 120 | // tran.SetAsync("MultiAsyncTestSet_class", Class); 121 | // TestClass t8 = null; 122 | // tasks.Add(tran.GetAsync("MultiAsyncTestSet_class").ContinueWith(t => t8 = t.Result)); 123 | 124 | // var ret = tran.Exec(); 125 | // Task.WaitAll(tasks.ToArray()); 126 | 127 | // Assert.Equal(10L, ret[0]); 128 | // Assert.Equal("", ret[2].ToString()); 129 | // Assert.Equal(String, ret[4].ToString()); 130 | // Assert.Equal(Bytes, ret[6]); 131 | // Assert.Equal(Class.ToString(), ret[8].ToString()); 132 | 133 | // Assert.Equal(10L, t1); 134 | // Assert.Equal("", t3); 135 | // Assert.Equal(String, t4); 136 | // Assert.Equal(Bytes, t6); 137 | // Assert.Equal(Class.ToString(), t8.ToString()); 138 | // } 139 | //} 140 | 141 | [Fact] 142 | public void Discard() 143 | { 144 | 145 | } 146 | 147 | [Fact] 148 | public void Exec() 149 | { 150 | 151 | } 152 | 153 | [Fact] 154 | public void UnWatch() 155 | { 156 | 157 | } 158 | 159 | [Fact] 160 | public void Watch() 161 | { 162 | 163 | } 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/RedisClientTests/ClusterTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading; 8 | using Xunit; 9 | 10 | namespace FreeRedis.Tests.RedisClientTests 11 | { 12 | public class ClusterTests : TestBase 13 | { 14 | [Fact] 15 | public void ClusterAddSlots() 16 | { 17 | 18 | } 19 | 20 | [Fact] 21 | public void ClusterBumpEpoch() 22 | { 23 | 24 | } 25 | 26 | [Fact] 27 | public void ClusterCountFailureReports() 28 | { 29 | 30 | } 31 | 32 | [Fact] 33 | public void ClusterCountKeysInSlot() 34 | { 35 | 36 | } 37 | 38 | [Fact] 39 | public void ClusterDelSlots() 40 | { 41 | 42 | } 43 | 44 | [Fact] 45 | public void ClusterFailOver() 46 | { 47 | 48 | } 49 | 50 | [Fact] 51 | public void ClusterFlushSlots() 52 | { 53 | 54 | } 55 | 56 | [Fact] 57 | public void ClusterForget() 58 | { 59 | 60 | } 61 | 62 | [Fact] 63 | public void ClusterGetKeysInSlot() 64 | { 65 | 66 | } 67 | 68 | [Fact] 69 | public void ClusterInfo() 70 | { 71 | 72 | } 73 | 74 | [Fact] 75 | public void ClusterKeySlot() 76 | { 77 | 78 | } 79 | 80 | [Fact] 81 | public void ClusterMeet() 82 | { 83 | 84 | } 85 | 86 | [Fact] 87 | public void ClusterMyId() 88 | { 89 | 90 | } 91 | 92 | [Fact] 93 | public void ClusterNodes() 94 | { 95 | 96 | } 97 | 98 | [Fact] 99 | public void ClusterReplicas() 100 | { 101 | 102 | } 103 | 104 | [Fact] 105 | public void ClusterReplicate() 106 | { 107 | 108 | } 109 | 110 | [Fact] 111 | public void ClusterReset() 112 | { 113 | 114 | } 115 | 116 | [Fact] 117 | public void ClusterSaveConfig() 118 | { 119 | 120 | } 121 | 122 | [Fact] 123 | public void ClusterSetConfigEpoch() 124 | { 125 | 126 | } 127 | 128 | [Fact] 129 | public void ClusterSetSlot() 130 | { 131 | 132 | } 133 | 134 | [Fact] 135 | public void ClusterSlaves() 136 | { 137 | 138 | } 139 | 140 | [Fact] 141 | public void ClusterSlots() 142 | { 143 | 144 | } 145 | 146 | [Fact] 147 | public void ReadOnly() 148 | { 149 | 150 | } 151 | 152 | [Fact] 153 | public void ReadWrite() 154 | { 155 | 156 | } 157 | 158 | 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/RedisClientTests/DelayQueueTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Xunit; 8 | using Xunit.Abstractions; 9 | 10 | namespace FreeRedis.Tests.RedisClientTests 11 | { 12 | public class DelayQueueTest(ITestOutputHelper output) 13 | { 14 | static readonly RedisClient _client = new RedisClient("127.0.0.1:6379,password=123"); 15 | 16 | [Fact] 17 | public async Task Test() 18 | { 19 | var delayQueue = _client.DelayQueue("TestDelayQueue"); 20 | 21 | //添加队列 22 | delayQueue.Enqueue($"Execute in 5 seconds.", TimeSpan.FromSeconds(5)); 23 | delayQueue.Enqueue($"Execute in 10 seconds.", DateTime.Now.AddSeconds(10)); 24 | delayQueue.Enqueue($"Execute in 15 seconds.", DateTime.Now.AddSeconds(15)); 25 | delayQueue.Enqueue($"Execute in 20 seconds.", TimeSpan.FromSeconds(20)); 26 | delayQueue.Enqueue($"Execute in 25 seconds.", DateTime.Now.AddSeconds(25)); 27 | delayQueue.Enqueue($"Execute in 2024-07-02 14:30:15", DateTime.Parse("2024-07-02 14:30:15")); 28 | 29 | 30 | //消费延时队列 31 | await delayQueue.DequeueAsync(s => 32 | { 33 | output.WriteLine($"{DateTime.Now}:{s}"); 34 | 35 | return Task.CompletedTask; 36 | }); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/RedisClientTests/GeoTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using Xunit; 8 | 9 | namespace FreeRedis.Tests.RedisClientTests 10 | { 11 | public class GeoTests : TestBase 12 | { 13 | [Fact] 14 | public void GetAdd() 15 | { 16 | cli.Del("TestGeoAdd"); 17 | Assert.Equal(3, cli.GeoAdd("TestGeoAdd", 18 | new GeoMember(10, 20, "m1"), 19 | new GeoMember(11, 21, "m2"), 20 | new GeoMember(12, 22, "m3"))); 21 | } 22 | 23 | [Fact] 24 | public void GeoDist() 25 | { 26 | cli.Del("TestGeoDist"); 27 | Assert.Equal(3, cli.GeoAdd("TestGeoDist", 28 | new GeoMember(10, 20, "m1"), 29 | new GeoMember(11, 21, "m2"), 30 | new GeoMember(12, 22, "m3"))); 31 | 32 | Assert.NotNull(cli.GeoDist("TestGeoDist", "m1", "m2")); 33 | Assert.NotNull(cli.GeoDist("TestGeoDist", "m1", "m3")); 34 | Assert.NotNull(cli.GeoDist("TestGeoDist", "m2", "m3")); 35 | Assert.Null(cli.GeoDist("TestGeoDist", "m1", "m31")); 36 | Assert.Null(cli.GeoDist("TestGeoDist", "m11", "m31")); 37 | } 38 | 39 | [Fact] 40 | public void GeoHash() 41 | { 42 | cli.Del("TestGeoHash"); 43 | Assert.Equal(3, cli.GeoAdd("TestGeoHash", 44 | new GeoMember(10, 20, "m1"), 45 | new GeoMember(11, 21, "m2"), 46 | new GeoMember(12, 22, "m3"))); 47 | 48 | Assert.False(string.IsNullOrEmpty(cli.GeoHash("TestGeoHash", "m1"))); 49 | Assert.Equal(2, cli.GeoHash("TestGeoHash", new[] { "m1", "m2" }).Select(a => string.IsNullOrEmpty(a) == false).Count()); 50 | Assert.Equal(2, cli.GeoHash("TestGeoHash", new[] { "m1", "m2", "m22" }).Where(a => string.IsNullOrEmpty(a) == false).Count()); 51 | } 52 | 53 | [Fact] 54 | public void GeoPos() 55 | { 56 | cli.Del("TestGeoPos"); 57 | Assert.Equal(3, cli.GeoAdd("TestGeoPos", 58 | new GeoMember(10, 20, "m1"), 59 | new GeoMember(11, 21, "m2"), 60 | new GeoMember(12, 22, "m3"))); 61 | 62 | Assert.Equal(4, cli.GeoPos("TestGeoPos", new[] { "m1", "m2", "m22", "m3" }).Length); 63 | //Assert.Equal((10, 20), rds.GeoPos("TestGeoPos", new[] { "m1", "m2", "m22", "m3" })[0]); 64 | //Assert.Equal((11, 21), rds.GeoPos("TestGeoPos", new[] { "m1", "m2", "m22", "m3" })[1]); 65 | Assert.Null(cli.GeoPos("TestGeoPos", new[] { "m1", "m2", "m22", "m3" })[2]); 66 | //Assert.Equal((12, 22), rds.GeoPos("TestGeoPos", new[] { "m1", "m2", "m22", "m3" })[3]); 67 | } 68 | 69 | [Fact] 70 | public void GeoRadius() 71 | { 72 | cli.Del("TestGeoRadius"); 73 | Assert.Equal(2, cli.GeoAdd("TestGeoRadius", 74 | new GeoMember(13.361389m, 38.115556m, "Palermo"), 75 | new GeoMember(15.087269m, 37.502669m, "Catania"))); 76 | 77 | var geopos = cli.GeoPos("TestGeoRadius", new[] { "m1", "Catania", "m2", "Palermo", "Catania2" }); 78 | 79 | var georadius1 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km); 80 | var georadius2 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, true); 81 | var georadius3 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, true, true); 82 | var georadius4 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, true, true, true); 83 | var georadius5 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, true, true, false); 84 | var georadius6 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, true, false); 85 | var georadius7 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, true, false, true); 86 | var georadius8 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, true, false, false); 87 | var georadius9 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, false, true, false); 88 | var georadius10 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, false, true, true); 89 | var georadius11 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, false, false, true); 90 | } 91 | 92 | [Fact] 93 | public void GeoRadiusByMember() 94 | { 95 | cli.Del("GeoRadiusByMember"); 96 | Assert.Equal(2, cli.GeoAdd("GeoRadiusByMember", 97 | new GeoMember(13.361389m, 38.115556m, "Palermo"), 98 | new GeoMember(15.087269m, 37.502669m, "Catania"))); 99 | 100 | var geopos = cli.GeoPos("GeoRadiusByMember", new[] { "m1", "Catania", "m2", "Palermo", "Catania2" }); 101 | 102 | var georadius1 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km); 103 | var georadius2 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, true); 104 | var georadius3 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, true, true); 105 | var georadius4 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, true, true, true); 106 | var georadius5 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, true, true, false); 107 | var georadius6 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, true, false); 108 | var georadius7 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, true, false, true); 109 | var georadius8 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, true, false, false); 110 | var georadius9 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, false, true, false); 111 | var georadius10 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, false, true, true); 112 | var georadius11 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, false, false, true); 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/RedisClientTests/HyperLogLogTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading; 8 | using Xunit; 9 | 10 | namespace FreeRedis.Tests.RedisClientTests 11 | { 12 | public class HyperLogLogTests : TestBase 13 | { 14 | [Fact] 15 | public void PfAdd() 16 | { 17 | var key1 = "PfAdd1"; 18 | cli.Del(key1); 19 | Assert.True(cli.PfAdd(key1, "a", "b", "c", "d", "e", "f", "g")); 20 | Assert.False(cli.PfAdd(key1, "a", "b", "c", "d", "e", "f", "g")); 21 | Assert.True(cli.PfAdd(key1, "a", "b", "c", "d", "e", "f", "g", "h")); 22 | } 23 | 24 | [Fact] 25 | public void PfCount() 26 | { 27 | var key1 = "PfCount1"; 28 | cli.Del(key1); 29 | Assert.True(cli.PfAdd(key1, "a", "b", "c", "d", "e", "f", "g")); 30 | Assert.Equal(7, cli.PfCount(key1)); 31 | 32 | var key2 = "PfCount2"; 33 | cli.Del(key2); 34 | Assert.True(cli.PfAdd(key2, "foo", "bar", "zap")); 35 | Assert.False(cli.PfAdd(key2, "zap", "zap", "zap")); 36 | Assert.False(cli.PfAdd(key2, "foo", "bar")); 37 | Assert.Equal(3, cli.PfCount(key2)); 38 | Assert.Equal(10, cli.PfCount(key1, key2)); 39 | Assert.Equal(10, cli.PfCount(key1, key2, Guid.NewGuid().ToString())); 40 | Assert.Equal(10, cli.PfCount(Guid.NewGuid().ToString(), key1, key2, Guid.NewGuid().ToString())); 41 | } 42 | 43 | [Fact] 44 | public void PfMerge() 45 | { 46 | var key1 = "PfMerge1"; 47 | cli.Del(key1); 48 | Assert.True(cli.PfAdd(key1, "foo", "bar", "zap", "a")); 49 | Assert.Equal(4, cli.PfCount(key1)); 50 | 51 | var key2 = "PfMerge2"; 52 | cli.Del(key2); 53 | Assert.True(cli.PfAdd(key2, "a", "b", "c", "foo")); 54 | Assert.Equal(4, cli.PfCount(key2)); 55 | 56 | var key3 = "PfMerge3"; 57 | cli.Del(key3); 58 | cli.PfMerge(key3, key1, key2); 59 | Assert.Equal(6, cli.PfCount(key3)); 60 | cli.PfMerge(key3, key1, key2, key3); 61 | Assert.Equal(6, cli.PfCount(key3)); 62 | 63 | cli.Del(key3); 64 | cli.PfMerge(key3, Guid.NewGuid().ToString()); 65 | Assert.Equal(0, cli.PfCount(key3)); 66 | 67 | cli.Del(key3); 68 | cli.PfMerge(key3, key1); 69 | Assert.Equal(4, cli.PfCount(key3)); 70 | 71 | cli.PfMerge(key3, key2); 72 | Assert.Equal(6, cli.PfCount(key3)); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/RedisClientTests/ModulesTests/CRC16Tests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using Xunit; 9 | 10 | namespace FreeRedis.Tests.RedisClientTests.Other 11 | { 12 | public class CRC16Tests 13 | { 14 | private static RedisClient cli = new RedisClient( 15 | new ConnectionStringBuilder[] 16 | { 17 | "192.168.0.41:6379", "192.168.0.42:6379", "192.168.0.43:6379", "192.168.0.44:6379", "192.168.0.45:6379", 18 | "192.168.0.46:6379" 19 | } 20 | ); 21 | 22 | [Fact] 23 | public void GetCRC16_1() 24 | { 25 | var r = cli.ClusterCRC16.GetCRC16("myKey"); 26 | Assert.Equal(32665, r); 27 | } 28 | [Fact] 29 | public void GetSlot() 30 | { 31 | var r = cli.ClusterCRC16.GetSlot("20220809_id"); 32 | Assert.Equal(3628, r); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/RedisClientTests/ModulesTests/LockTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Xunit; 8 | 9 | namespace FreeRedis.Tests.RedisClientTests.Other 10 | { 11 | public class LockTests : TestBase 12 | { 13 | [Fact] 14 | public void Lock1() 15 | { 16 | var tasks = new Task[4]; 17 | for (var a = 0; a < tasks.Length; a++) 18 | tasks[a] = Task.Run(() => { 19 | var lk = cli.Lock("testlock1", 10); 20 | Thread.CurrentThread.Join(1000); 21 | Assert.True(lk.Unlock()); 22 | }); 23 | Task.WaitAll(tasks); 24 | } 25 | 26 | [Fact] 27 | public void Lock2() 28 | { 29 | using (cli.Lock("testlock2", 100)) 30 | { 31 | Thread.CurrentThread.Join(5000); 32 | } 33 | } 34 | 35 | [Fact] 36 | public void Lock3() 37 | { 38 | using (cli.Lock("testlock3", 5)) 39 | { 40 | Thread.CurrentThread.Join(10000); 41 | } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/RedisClientTests/PubSubTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading; 9 | using Xunit; 10 | 11 | namespace FreeRedis.Tests.RedisClientTests.Other 12 | { 13 | public class PubSubTests : TestBase 14 | { 15 | [Fact] 16 | public void PSubscribe() 17 | { 18 | //see Subscribe 19 | } 20 | 21 | [Fact] 22 | public void Publish() 23 | { 24 | var key1 = "Publish1"; 25 | Assert.Equal(0, cli.Publish(key1, "test")); 26 | } 27 | 28 | [Fact] 29 | public void PubSubChannels() 30 | { 31 | RedisScopeExecHelper.ExecScope(Connection, (cli) => 32 | { 33 | var key1 = "PubSubChannels1"; 34 | using (cli.Subscribe(key1, (chan, msg) => 35 | { 36 | 37 | })) 38 | { 39 | var chans = cli.PubSubChannels("PubSubChannels1*"); 40 | Assert.Single(chans); 41 | Assert.Equal(key1, chans[0]); 42 | Thread.CurrentThread.Join(500); 43 | } 44 | }); 45 | } 46 | 47 | [Fact] 48 | public void PubSubNumSub() 49 | { 50 | RedisScopeExecHelper.ExecScope(Connection, (cli) => 51 | { 52 | var key1 = "PubSubNumSub1"; 53 | using (cli.Subscribe(key1, (chan, msg) => 54 | { 55 | 56 | })) 57 | { 58 | var r1 = cli.PubSubNumSub("PubSubNumSub1"); 59 | Assert.Equal(1, r1); 60 | 61 | var r2 = cli.PubSubNumSub(new[] { "PubSubNumSub1" }); 62 | Assert.Single(r2); 63 | Assert.Equal(1, r2[0]); 64 | 65 | Thread.CurrentThread.Join(500); 66 | } 67 | }); 68 | } 69 | 70 | [Fact] 71 | public void PubSubNumPat() 72 | { 73 | cli.PubSubNumPat(); 74 | } 75 | 76 | [Fact] 77 | public void PUnSubscribe() 78 | { 79 | } 80 | 81 | [Fact] 82 | public void Subscribe() 83 | { 84 | var key1 = "Subscribe1"; 85 | var key2 = "Subscribe2"; 86 | 87 | bool isbreak = false; 88 | new Thread(() => 89 | { 90 | while (isbreak == false) 91 | { 92 | cli.Publish(key1, Guid.NewGuid().ToString()); 93 | cli.Publish(key2, Guid.NewGuid().ToString()); 94 | cli.Publish("randomSubscribe1", Guid.NewGuid().ToString()); 95 | Thread.CurrentThread.Join(100); 96 | } 97 | }).Start(); 98 | 99 | using (cli.Subscribe(key1, ondata)) 100 | { 101 | using (cli.Subscribe(key2, ondata)) 102 | { 103 | using (cli.PSubscribe("*", ondata)) 104 | { 105 | Thread.CurrentThread.Join(2000); 106 | } 107 | Thread.CurrentThread.Join(2000); 108 | } 109 | Thread.CurrentThread.Join(2000); 110 | } 111 | Trace.WriteLine("one more time"); 112 | using (cli.Subscribe(key1, ondata)) 113 | { 114 | using (cli.Subscribe(key2, ondata)) 115 | { 116 | using (cli.PSubscribe("*", ondata)) 117 | { 118 | Thread.CurrentThread.Join(2000); 119 | } 120 | Thread.CurrentThread.Join(2000); 121 | } 122 | Thread.CurrentThread.Join(2000); 123 | } 124 | void ondata(string channel, object data) 125 | { 126 | Trace.WriteLine($"{channel} -> {data}"); 127 | } 128 | isbreak = true; 129 | } 130 | 131 | [Fact] 132 | public void UnSubscribe() 133 | { 134 | } 135 | 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/RedisClientTests/ScriptingTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading; 8 | using Xunit; 9 | 10 | namespace FreeRedis.Tests.RedisClientTests 11 | { 12 | public class ScriptingTests : TestBase 13 | { 14 | [Fact] 15 | public void Eval() 16 | { 17 | using (var sh = cli.GetDatabase()) 18 | { 19 | var r1 = sh.Eval("return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", new[] { "key1", "key2" }, "first", "second") as object[]; 20 | Assert.NotNull(r1); 21 | Assert.True(r1.Length == 4); 22 | Assert.Equal("key1", r1[0]); 23 | Assert.Equal("key2", r1[1]); 24 | Assert.Equal("first", r1[2]); 25 | Assert.Equal("second", r1[3]); 26 | Assert.Equal("OK", sh.Eval($"return redis.call('set','{Guid.NewGuid()}','bar')")); 27 | Assert.Equal("OK", sh.Eval("return redis.call('set',KEYS[1],'bar')", new[] { Guid.NewGuid().ToString() })); 28 | 29 | //RESP3 30 | Assert.Equal(10L, sh.Eval("return 10")); 31 | var r2 = sh.Eval("return {1,2,{3,'Hello World!'}}") as object[]; 32 | Assert.NotNull(r2); 33 | Assert.True(r2.Length == 3); 34 | Assert.Equal(1L, r2[0]); 35 | Assert.Equal(2L, r2[1]); 36 | var r3 = r2[2] as object[]; 37 | Assert.Equal(3L, r3[0]); 38 | Assert.Equal("Hello World!", r3[1]); 39 | 40 | var r4 = sh.Eval("return {1,2,3.3333,somekey='somevalue','foo',nil,'bar'}") as object[]; 41 | //As you can see 3.333 is converted into 3, somekey is excluded, and the bar string is never returned as there is a nil before. 42 | Assert.NotNull(r4); 43 | Assert.True(r4.Length == 4); 44 | Assert.Equal(1L, r4[0]); 45 | Assert.Equal(2L, r4[1]); 46 | Assert.Equal(3L, r4[2]); 47 | Assert.Equal("foo", r4[3]); 48 | 49 | Assert.Equal("My Error", Assert.Throws(() => sh.Eval("return {err=\"My Error\"}"))?.Message); 50 | Assert.Equal("My Error222", Assert.Throws(() => sh.Eval("return redis.error_reply(\"My Error222\")"))?.Message); 51 | 52 | var key1 = Guid.NewGuid().ToString(); 53 | Assert.Equal(1, sh.LPush(key1, "a")); 54 | Assert.True(Assert.Throws(() => sh.Eval($"return redis.call('get','{key1}')"))?.Message.Contains("ERR Error running script (call to ") == true); 55 | //(error) ERR Error running script (call to f_6b1bf486c81ceb7edf3c093f4c48582e38c0e791): ERR Operation against a key holding the wrong kind of value 56 | } 57 | } 58 | 59 | [Fact] 60 | public void EvalSha() 61 | { 62 | var scriptid = cli.ScriptLoad("return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"); 63 | Assert.True(!string.IsNullOrWhiteSpace(scriptid)); 64 | 65 | var r1 = cli.EvalSha(scriptid, new[] { "key1", "key2" }, "first", "second") as object[]; 66 | Assert.NotNull(r1); 67 | Assert.True(r1.Length == 4); 68 | Assert.Equal("key1", r1[0]); 69 | Assert.Equal("key2", r1[1]); 70 | Assert.Equal("first", r1[2]); 71 | Assert.Equal("second", r1[3]); 72 | } 73 | 74 | [Fact] 75 | public void ScriptExists() 76 | { 77 | cli.ScriptFlush(); 78 | var r1 = cli.ScriptLoad("return redis.call('get','foo')"); 79 | Assert.True(!string.IsNullOrWhiteSpace(r1)); 80 | Assert.True(cli.ScriptExists(r1)); 81 | Assert.False(cli.ScriptExists("6b1bf486c81ceb7edf3c193f4c48582e38c0e791")); 82 | 83 | var r2 = cli.ScriptLoad("return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"); 84 | Assert.True(!string.IsNullOrWhiteSpace(r2)); 85 | Assert.True(cli.ScriptExists(r2)); 86 | 87 | var r3 = cli.ScriptExists(new[] { r1, "6b1bf486c81ceb7edf3c193f4c48582e38c0e791", r2 }); 88 | Assert.Equal(3, r3.Length); 89 | Assert.True(r3[0]); 90 | Assert.False(r3[1]); 91 | Assert.True(r3[2]); 92 | 93 | cli.ScriptFlush(); 94 | Assert.False(cli.ScriptExists(r1)); 95 | Assert.False(cli.ScriptExists("6b1bf486c81ceb7edf3c193f4c48582e38c0e791")); 96 | Assert.False(cli.ScriptExists(r2)); 97 | r3 = cli.ScriptExists(new[] { r1, "6b1bf486c81ceb7edf3c193f4c48582e38c0e791", r2 }); 98 | Assert.Equal(3, r3.Length); 99 | Assert.False(r3[0]); 100 | Assert.False(r3[1]); 101 | Assert.False(r3[2]); 102 | } 103 | 104 | [Fact] 105 | public void ScriptFlush() 106 | { 107 | //cli.ScriptFlush(); 108 | } 109 | 110 | [Fact] 111 | public void ScriptKill() 112 | { 113 | Assert.Equal("NOTBUSY No scripts in execution right now.", Assert.Throws(() => cli.ScriptKill())?.Message); 114 | } 115 | 116 | [Fact] 117 | public void ScriptLoad() 118 | { 119 | var r1 = cli.ScriptLoad("return redis.call('get','foo')"); 120 | Assert.True(!string.IsNullOrWhiteSpace(r1)); 121 | } 122 | 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/RedisEnvironmentHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace FreeRedis.Tests 4 | { 5 | public static class RedisEnvironmentHelper 6 | { 7 | public static string GetHost(string serviceName) 8 | { 9 | return Environment.GetEnvironmentVariable($"DOCKER_HOST_{serviceName}"); 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/RedisScopeExecHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace FreeRedis.Tests 4 | { 5 | public static class RedisScopeExecHelper 6 | { 7 | public static void ExecScope(string connectionString, Action func) 8 | { 9 | using (var scope = new RedisClient(RedisEnvironmentHelper.GetHost(connectionString))) 10 | { 11 | func.Invoke(scope); 12 | } 13 | } 14 | 15 | public static void ExecScope(ConnectionStringBuilder connectionStringBuilder, Action func) 16 | { 17 | using (var scope = new RedisClient(connectionStringBuilder)) 18 | { 19 | func.Invoke(scope); 20 | } 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/TestBase.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Text; 6 | 7 | namespace FreeRedis.Tests 8 | { 9 | public class TestBase 10 | { 11 | protected static ConnectionStringBuilder Connection = new ConnectionStringBuilder() 12 | { 13 | Host = "127.0.0.1", // RedisEnvironmentHelper.GetHost("redis_single"), 14 | //Password = "123456", 15 | Database = 1, 16 | MaxPoolSize = 10, 17 | Protocol = RedisProtocol.RESP2, 18 | ClientName = "FreeRedis" 19 | }; 20 | //static Lazy _cliLazy = new Lazy(() => new RedisClient("127.0.0.1:6379,database=1", "127.0.0.1:6379,database=1")); 21 | static Lazy _cliLazy = new Lazy(() => 22 | { 23 | //var r = new RedisClient(new ConnectionStringBuilder[] { "127.0.0.1:6379,database=1,password=123" }); //redis 3.2 cluster 24 | //var r = new RedisClient("127.0.0.1:6379,database=1"); //redis 3.2 25 | //var r = new RedisClient("127.0.0.1:6379,database=1", "127.0.0.1:6379,database=1"); 26 | var r = new RedisClient(Connection); //redis 6.0 27 | // var r = new RedisClient(connectionString); //redis 6.0 28 | r.Serialize = obj => JsonConvert.SerializeObject(obj); 29 | r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type); 30 | r.Notice += (s, e) => Trace.WriteLine(e.Log); 31 | return r; 32 | }); 33 | public static RedisClient cli => _cliLazy.Value; 34 | 35 | protected readonly object Null = null; 36 | protected readonly string String = "我是中国人"; 37 | protected readonly byte[] Bytes = Encoding.UTF8.GetBytes("这是一个byte字节"); 38 | protected readonly TestClass Class = new TestClass { Id = 1, Name = "Class名称", CreateTime = DateTime.Now, TagId = new[] { 1, 3, 3, 3, 3 } }; 39 | 40 | public TestBase() { 41 | //rds.NodesServerManager.FlushAll(); 42 | } 43 | } 44 | 45 | public class TestClass { 46 | public int Id { get; set; } 47 | public string Name { get; set; } 48 | public DateTime CreateTime { get; set; } 49 | 50 | public int[] TagId { get; set; } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /test/Unit/FreeRedis.Tests/Utils.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using Xunit; 5 | 6 | namespace FreeRedis.Tests 7 | { 8 | public static class Utils 9 | { 10 | public static void SetGetTest(this RedisClient cli) 11 | { 12 | var key = Guid.NewGuid().ToString(); 13 | cli.Set(key, key); 14 | Assert.Equal(key, cli.Get(key)); 15 | } 16 | } 17 | } 18 | --------------------------------------------------------------------------------