瀏覽代碼

去除CSRedisCore、Caching.CSRedis,改用FreeRedis、FreeRedis.DistributedCache
重写RedisCacheTool方法,更新限流分布式缓存

zhontai 2 年之前
父節點
當前提交
1f5f62a14a

+ 0 - 4
src/hosts/ZhonTai.Host/ZhonTai.Host.csproj

@@ -9,10 +9,6 @@
 		<NoWarn>1701;1702;1591</NoWarn>
 	</PropertyGroup>
 
-	<ItemGroup>
-	  <None Remove="Configs\createdbsql.txt" />
-	</ItemGroup>
-
 	<ItemGroup>
 	  <Content Include="Configs\createdbsql.txt">
 	    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>

+ 6 - 3
src/platform/ZhonTai.Admin/Core/Extensions/RateLimitServiceCollectionExtensions.cs

@@ -1,8 +1,9 @@
 using AspNetCoreRateLimit;
+using FreeRedis;
 using Microsoft.Extensions.Caching.Distributed;
-using Microsoft.Extensions.Caching.Redis;
 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.DependencyInjection;
+using Newtonsoft.Json;
 using ZhonTai.Admin.Tools.Cache;
 
 namespace ZhonTai.Admin.Core.Extensions;
@@ -25,8 +26,10 @@ public static class RateLimitServiceCollectionExtensions
         if (cacheConfig.TypeRateLimit == CacheType.Redis)
         {
             //redis
-            var redisRateLimit = new CSRedis.CSRedisClient(cacheConfig.Redis.ConnectionStringRateLimit);
-            services.AddSingleton<IDistributedCache>(new CSRedisCache(redisRateLimit));
+            var redis = new RedisClient(cacheConfig.Redis.ConnectionStringRateLimit);
+            redis.Serialize = JsonConvert.SerializeObject;
+            redis.Deserialize = JsonConvert.DeserializeObject;
+            services.AddSingleton<IDistributedCache>(new DistributedCache(redis));
             services.AddDistributedRateLimiting();
         }
         else

+ 5 - 2
src/platform/ZhonTai.Admin/Core/HostApp.cs

@@ -54,6 +54,7 @@ using ZhonTai.DynamicApi.Attributes;
 using System.Text.RegularExpressions;
 using Swashbuckle.AspNetCore.SwaggerGen;
 using System.Text.Json.Serialization;
+using FreeRedis;
 
 namespace ZhonTai.Admin.Core;
 
@@ -557,8 +558,10 @@ public partial class HostApp
         var cacheConfig = ConfigHelper.Get<CacheConfig>("cacheconfig", env.EnvironmentName);
         if (cacheConfig.Type == CacheType.Redis)
         {
-            var csredis = new CSRedis.CSRedisClient(cacheConfig.Redis.ConnectionString);
-            RedisHelper.Initialization(csredis);
+            var redis = new RedisClient(cacheConfig.Redis.ConnectionString);
+            redis.Serialize = JsonConvert.SerializeObject;
+            redis.Deserialize = JsonConvert.DeserializeObject;
+            services.AddSingleton(redis);
             services.AddSingleton<ICacheTool, RedisCacheTool>();
         }
         else

+ 3 - 11
src/platform/ZhonTai.Admin/Tools/Cache/ICacheTool.cs

@@ -77,7 +77,7 @@ public interface ICacheTool
     /// </summary>
     /// <param name="key">键</param>
     /// <param name="value">值</param>
-    bool Set(string key, object value);
+    void Set(string key, object value);
 
     /// <summary>
     /// 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象
@@ -85,15 +85,7 @@ public interface ICacheTool
     /// <param name="key">键</param>
     /// <param name="value">值</param>
     /// <param name="expire">有效期</param>
-    bool Set(string key, object value, TimeSpan expire);
-
-    /// <summary>
-    /// 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象
-    /// </summary>
-    /// <param name="key">键</param>
-    /// <param name="value">值</param>
-    /// <returns></returns>
-    Task<bool> SetAsync(string key, object value);
+    void Set(string key, object value, TimeSpan expire);
 
     /// <summary>
     /// 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象
@@ -102,7 +94,7 @@ public interface ICacheTool
     /// <param name="value">值</param>
     /// <param name="expire">有效期</param>
     /// <returns></returns>
-    Task<bool> SetAsync(string key, object value, TimeSpan expire);
+    Task SetAsync(string key, object value, TimeSpan? expire = null);
 
     /// <summary>
     /// 获取或设置缓存

+ 17 - 15
src/platform/ZhonTai.Admin/Tools/Cache/MemoryCacheTool.cs

@@ -13,8 +13,11 @@ namespace ZhonTai.Admin.Tools.Cache;
 /// <summary>
 /// 内存缓存
 /// </summary>
-public class MemoryCacheTool : ICacheTool
+public partial class MemoryCacheTool : ICacheTool
 {
+    [GeneratedRegex("\\{.*\\}")]
+    private static partial Regex PatternRegex();
+
     private readonly IMemoryCache _memoryCache;
     public MemoryCacheTool(IMemoryCache memoryCache)
     {
@@ -45,7 +48,7 @@ public class MemoryCacheTool : ICacheTool
         if (pattern.IsNull())
             return default;
 
-        pattern = Regex.Replace(pattern, @"\{.*\}", "(.*)");
+        pattern = PatternRegex().Replace(pattern, "(.*)");
 
         var keys = GetAllKeys().Where(k => Regex.IsMatch(k, pattern));
 
@@ -87,28 +90,27 @@ public class MemoryCacheTool : ICacheTool
         return Task.FromResult(Get<T>(key));
     }
 
-    public bool Set(string key, object value)
+    public void Set(string key, object value)
     {
         _memoryCache.Set(key, value);
-        return true;
     }
 
-    public bool Set(string key, object value, TimeSpan expire)
+    public void Set(string key, object value, TimeSpan expire)
     {
         _memoryCache.Set(key, value, expire);
-        return true;
     }
 
-    public Task<bool> SetAsync(string key, object value)
+    public Task SetAsync(string key, object value, TimeSpan? expire = null)
     {
-        Set(key, value);
-        return Task.FromResult(true);
-    }
-
-    public Task<bool> SetAsync(string key, object value, TimeSpan expire)
-    {
-        Set(key, value, expire);
-        return Task.FromResult(true);
+        if(expire.HasValue)
+        {
+            Set(key, value, expire.Value);
+        }
+        else
+        {
+            Set(key, value);
+        }
+        return Task.CompletedTask;
     }
 
     public async Task<T> GetOrSetAsync<T>(string key, Func<Task<T>> func, TimeSpan? expire = null)

+ 33 - 35
src/platform/ZhonTai.Admin/Tools/Cache/RedisCacheTool.cs

@@ -1,22 +1,32 @@
-using System;
+using FreeRedis;
+using System;
 using System.Text.RegularExpressions;
 using System.Threading.Tasks;
+using ZhonTai.Common.Extensions;
 
 namespace ZhonTai.Admin.Tools.Cache;
 
 /// <summary>
 /// Redis缓存
 /// </summary>
-public class RedisCacheTool : ICacheTool
+public partial class RedisCacheTool : ICacheTool
 {
+    [GeneratedRegex("\\{.*\\}")]
+    private static partial Regex PatternRegex();
+
+    private readonly RedisClient _redisClient;
+    public RedisCacheTool(RedisClient redisClient)
+    {
+        _redisClient = redisClient;
+    }
     public long Del(params string[] key)
     {
-        return RedisHelper.Del(key);
+        return _redisClient.Del(key);
     }
 
     public Task<long> DelAsync(params string[] key)
     {
-        return RedisHelper.DelAsync(key);
+        return _redisClient.DelAsync(key);
     }
 
     public async Task<long> DelByPatternAsync(string pattern)
@@ -24,12 +34,12 @@ public class RedisCacheTool : ICacheTool
         if (pattern.IsNull())
             return default;
 
-        pattern = Regex.Replace(pattern, @"\{.*\}", "*");
+        pattern = PatternRegex().Replace(pattern, "*");
 
-        var keys = (await RedisHelper.KeysAsync(pattern));
+        var keys = await _redisClient.KeysAsync(pattern);
         if (keys != null && keys.Length > 0)
         {
-            return await RedisHelper.DelAsync(keys);
+            return await _redisClient.DelAsync(keys);
         }
 
         return default;
@@ -37,78 +47,66 @@ public class RedisCacheTool : ICacheTool
 
     public bool Exists(string key)
     {
-        return RedisHelper.Exists(key);
+        return _redisClient.Exists(key);
     }
 
     public Task<bool> ExistsAsync(string key)
     {
-        return RedisHelper.ExistsAsync(key);
+        return _redisClient.ExistsAsync(key);
     }
 
     public string Get(string key)
     {
-        return RedisHelper.Get(key);
+        return _redisClient.Get(key);
     }
 
     public T Get<T>(string key)
     {
-        return RedisHelper.Get<T>(key);
+        return _redisClient.Get<T>(key);
     }
 
     public Task<string> GetAsync(string key)
     {
-        return RedisHelper.GetAsync(key);
+        return _redisClient.GetAsync(key);
     }
 
     public Task<T> GetAsync<T>(string key)
     {
-        return RedisHelper.GetAsync<T>(key);
-    }
-
-    public bool Set(string key, object value)
-    {
-        return RedisHelper.Set(key, value);
+        return _redisClient.GetAsync<T>(key);
     }
 
-    public bool Set(string key, object value, TimeSpan expire)
+    public void Set(string key, object value)
     {
-        return RedisHelper.Set(key, value, expire);
+        _redisClient.Set(key, value);
     }
 
-    public Task<bool> SetAsync(string key, object value)
+    public void Set(string key, object value, TimeSpan expire)
     {
-        return RedisHelper.SetAsync(key, value);
+        _redisClient.Set(key, value, expire);
     }
 
-    public Task<bool> SetAsync(string key, object value, TimeSpan expire)
+    public Task SetAsync(string key, object value, TimeSpan? expire = null)
     {
-        return RedisHelper.SetAsync(key, value, expire);
+        return _redisClient.SetAsync(key, value, expire.HasValue ? expire.Value.TotalSeconds.ToInt() : 0);
     }
 
     public async Task<T> GetOrSetAsync<T>(string key, Func<Task<T>> func, TimeSpan? expire = null)
     {
-        if (await RedisHelper.ExistsAsync(key))
+        if (await _redisClient.ExistsAsync(key))
         {
             try
             {
-                return await RedisHelper.GetAsync<T>(key);
+                return await _redisClient.GetAsync<T>(key);
             }
             catch
             {
-                await RedisHelper.DelAsync(key);
+                await _redisClient.DelAsync(key);
             }
         }
 
         var result = await func.Invoke();
 
-        if (expire.HasValue)
-        {
-            await RedisHelper.SetAsync(key, result, expire.Value);
-        }
-        else
-        {
-            await RedisHelper.SetAsync(key, result);
-        }
+        await _redisClient.SetAsync(key, result, expire.HasValue ? expire.Value.TotalSeconds.ToInt() : 0);
 
         return result;
     }

+ 2 - 2
src/platform/ZhonTai.Admin/ZhonTai.Admin.csproj

@@ -13,9 +13,9 @@
 		<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="8.0.0" />
 		<PackageReference Include="Autofac.Extras.DynamicProxy" Version="6.0.1" />
 		<PackageReference Include="Castle.Core.AsyncInterceptor" Version="2.1.0" />
-		<PackageReference Include="CSRedisCore" Version="3.8.670" />
-		<PackageReference Include="Caching.CSRedis" Version="3.8.670" />
 		<PackageReference Include="FluentValidation.AspNetCore" Version="11.2.2" />
+		<PackageReference Include="FreeRedis" Version="1.0.7" />
+		<PackageReference Include="FreeRedis.DistributedCache" Version="1.0.5" />
 		<PackageReference Include="FreeSql" Version="3.2.690" />
 		<PackageReference Include="FreeSql.Cloud" Version="1.6.3" />
 		<PackageReference Include="FreeSql.Repository" Version="3.2.690" />

+ 53 - 9
src/platform/ZhonTai.Admin/ZhonTai.Admin.xml

@@ -6996,15 +6996,7 @@
             <param name="value">值</param>
             <param name="expire">有效期</param>
         </member>
-        <member name="M:ZhonTai.Admin.Tools.Cache.ICacheTool.SetAsync(System.String,System.Object)">
-            <summary>
-            设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象
-            </summary>
-            <param name="key">键</param>
-            <param name="value">值</param>
-            <returns></returns>
-        </member>
-        <member name="M:ZhonTai.Admin.Tools.Cache.ICacheTool.SetAsync(System.String,System.Object,System.TimeSpan)">
+        <member name="M:ZhonTai.Admin.Tools.Cache.ICacheTool.SetAsync(System.String,System.Object,System.Nullable{System.TimeSpan})">
             <summary>
             设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象
             </summary>
@@ -7028,11 +7020,31 @@
             内存缓存
             </summary>
         </member>
+        <member name="M:ZhonTai.Admin.Tools.Cache.MemoryCacheTool.PatternRegex">
+            <remarks>
+            Pattern explanation:<br/>
+            <code>
+            ○ Match '{'.<br/>
+            ○ Match a character other than '\n' greedily any number of times.<br/>
+            ○ Match '}'.<br/>
+            </code>
+            </remarks>
+        </member>
         <member name="T:ZhonTai.Admin.Tools.Cache.RedisCacheTool">
             <summary>
             Redis缓存
             </summary>
         </member>
+        <member name="M:ZhonTai.Admin.Tools.Cache.RedisCacheTool.PatternRegex">
+            <remarks>
+            Pattern explanation:<br/>
+            <code>
+            ○ Match '{'.<br/>
+            ○ Match a character other than '\n' greedily any number of times.<br/>
+            ○ Match '}'.<br/>
+            </code>
+            </remarks>
+        </member>
         <member name="P:ZhonTai.Admin.Tools.Captcha.CaptchaInput.Token">
             <summary>
             校验唯一标识
@@ -7238,6 +7250,38 @@
             <param name="inputSpan">The text being scanned by the regular expression.</param>
             <returns>true if a possible match was found; false if no more matches are possible.</returns>
         </member>
+        <member name="T:System.Text.RegularExpressions.Generated.PatternRegex_1">
+            <summary>Custom <see cref="T:System.Text.RegularExpressions.Regex"/>-derived type for the PatternRegex method.</summary>
+        </member>
+        <member name="F:System.Text.RegularExpressions.Generated.PatternRegex_1.Instance">
+            <summary>Cached, thread-safe singleton instance.</summary>
+        </member>
+        <member name="M:System.Text.RegularExpressions.Generated.PatternRegex_1.#ctor">
+            <summary>Initializes the instance.</summary>
+        </member>
+        <member name="T:System.Text.RegularExpressions.Generated.PatternRegex_1.RunnerFactory">
+            <summary>Provides a factory for creating <see cref="T:System.Text.RegularExpressions.RegexRunner"/> instances to be used by methods on <see cref="T:System.Text.RegularExpressions.Regex"/>.</summary>
+        </member>
+        <member name="M:System.Text.RegularExpressions.Generated.PatternRegex_1.RunnerFactory.CreateInstance">
+            <summary>Creates an instance of a <see cref="T:System.Text.RegularExpressions.RegexRunner"/> used by methods on <see cref="T:System.Text.RegularExpressions.Regex"/>.</summary>
+        </member>
+        <member name="T:System.Text.RegularExpressions.Generated.PatternRegex_1.RunnerFactory.Runner">
+            <summary>Provides the runner that contains the custom logic implementing the specified regular expression.</summary>
+        </member>
+        <member name="M:System.Text.RegularExpressions.Generated.PatternRegex_1.RunnerFactory.Runner.Scan(System.ReadOnlySpan{System.Char})">
+            <summary>Scan the <paramref name="inputSpan"/> starting from base.runtextstart for the next match.</summary>
+            <param name="inputSpan">The text being scanned by the regular expression.</param>
+        </member>
+        <member name="M:System.Text.RegularExpressions.Generated.PatternRegex_1.RunnerFactory.Runner.TryFindNextPossibleStartingPosition(System.ReadOnlySpan{System.Char})">
+            <summary>Search <paramref name="inputSpan"/> starting from base.runtextpos for the next location a match could possibly start.</summary>
+            <param name="inputSpan">The text being scanned by the regular expression.</param>
+            <returns>true if a possible match was found; false if no more matches are possible.</returns>
+        </member>
+        <member name="M:System.Text.RegularExpressions.Generated.PatternRegex_1.RunnerFactory.Runner.TryMatchAtCurrentPosition(System.ReadOnlySpan{System.Char})">
+            <summary>Determine whether <paramref name="inputSpan"/> at base.runtextpos is a match for the regular expression.</summary>
+            <param name="inputSpan">The text being scanned by the regular expression.</param>
+            <returns>true if the regular expression matches at the current position; otherwise, false.</returns>
+        </member>
         <member name="T:System.Text.RegularExpressions.Generated.Utilities">
             <summary>Helper methods used by generated <see cref="T:System.Text.RegularExpressions.Regex"/>-derived implementations.</summary>
         </member>