-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathRedisCacheClientBase.cs
239 lines (208 loc) · 8.95 KB
/
RedisCacheClientBase.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
namespace Masa.Contrib.Caching.Distributed.StackExchangeRedis;
public abstract class RedisCacheClientBase : DistributedCacheClientBase
{
protected static readonly Guid UniquelyIdentifies = Guid.NewGuid();
protected ISubscriber Subscriber;
protected IDatabase Db;
protected readonly JsonSerializerOptions GlobalJsonSerializerOptions;
protected CacheEntryOptions GlobalCacheEntryOptions;
protected CacheOptions GlobalCacheOptions;
protected RedisCacheClientBase(RedisConfigurationOptions redisConfigurationOptions,
JsonSerializerOptions? jsonSerializerOptions)
{
GlobalCacheOptions = redisConfigurationOptions.GlobalCacheOptions;
var redisConfiguration = GetRedisConfigurationOptions(redisConfigurationOptions);
IConnectionMultiplexer? connection = ConnectionMultiplexer.Connect(redisConfiguration);
Db = connection.GetDatabase();
Subscriber = connection.GetSubscriber();
GlobalJsonSerializerOptions = jsonSerializerOptions ?? new JsonSerializerOptions().EnableDynamicTypes();
GlobalCacheEntryOptions = new CacheEntryOptions
{
AbsoluteExpiration = redisConfiguration.AbsoluteExpiration,
AbsoluteExpirationRelativeToNow = redisConfiguration.AbsoluteExpirationRelativeToNow,
SlidingExpiration = redisConfiguration.SlidingExpiration
};
}
private static RedisConfigurationOptions GetRedisConfigurationOptions(RedisConfigurationOptions redisConfigurationOptions)
{
if (redisConfigurationOptions.Servers.Any())
return redisConfigurationOptions;
return new RedisConfigurationOptions()
{
Servers = new List<RedisServerOptions>()
{
new()
}
};
}
protected T? ConvertToValue<T>(RedisValue value, out bool isExist)
{
if (value.HasValue && !value.IsNullOrEmpty)
{
isExist = true;
return value.ConvertToValue<T>(GlobalJsonSerializerOptions);
}
isExist = false;
return default;
}
protected CacheEntryOptions GetCacheEntryOptions(CacheEntryOptions? options = null)
=> options ?? GlobalCacheEntryOptions;
protected CacheOptions GetCacheOptions(Action<CacheOptions>? action)
{
if (action != null)
{
CacheOptions cacheOptions = new CacheOptions();
action.Invoke(cacheOptions);
return cacheOptions;
}
return GlobalCacheOptions;
}
protected static PublishOptions GetAndCheckPublishOptions(string channel, Action<PublishOptions> setup)
{
ArgumentNullException.ThrowIfNull(channel);
ArgumentNullException.ThrowIfNull(setup);
var options = new PublishOptions(UniquelyIdentifies);
setup.Invoke(options);
options.Key.CheckIsNullOrWhiteSpace();
return options;
}
internal void RefreshCore(List<DataCacheModel> models, CancellationToken token = default)
{
var awaitRefreshOptions = GetKeyAndExpireList(models, token);
if (awaitRefreshOptions.Count > 0)
{
Db.ScriptEvaluate(Const.SET_EXPIRE_SCRIPT,
awaitRefreshOptions.Select(item => item.Key).GetRedisKeys(),
awaitRefreshOptions.Select(item => (RedisValue)(item.Value?.TotalSeconds ?? -1)).ToArray()
);
}
}
internal async Task RefreshCoreAsync(
List<DataCacheModel> models,
CancellationToken token = default)
{
var awaitRefreshOptions = GetKeyAndExpireList(models, token);
if (awaitRefreshOptions.Count > 0)
{
await Db.ScriptEvaluateAsync(Const.SET_EXPIRE_SCRIPT,
awaitRefreshOptions.Select(item => item.Key).GetRedisKeys(),
awaitRefreshOptions.Select(item => (RedisValue)(item.Value?.TotalSeconds ?? -1)).ToArray()
);
}
}
internal List<DataCacheModel> GetListByKeyPattern(string keyPattern)
=> GetListCoreByKeyPattern(keyPattern, (script, parameters) => Db.ScriptEvaluate(LuaScript.Prepare(script), parameters)
.ToDictionary());
internal Task<List<DataCacheModel>> GetListByKeyPatternAsync(string keyPattern)
=> Task.FromResult(GetListCoreByKeyPattern(keyPattern, (script, parameters) => Db
.ScriptEvaluateAsync(LuaScript.Prepare(script), parameters)
.ConfigureAwait(false)
.GetAwaiter()
.GetResult()
.ToDictionary()));
private static List<DataCacheModel> GetListCoreByKeyPattern(
string keyPattern,
Func<string, object, Dictionary<string, RedisResult>> func)
{
var arrayRedisResult = func.Invoke(
Const.GET_KEY_AND_VALUE_SCRIPT,
new
{
keypattern = keyPattern
});
List<DataCacheModel> list = new List<DataCacheModel>();
foreach (var redisResult in arrayRedisResult)
{
var byteArray = (RedisValue[])redisResult.Value;
list.Add(MapMetadataByAutomatic(redisResult.Key, byteArray));
}
return list;
}
internal List<DataCacheModel> GetList(IEnumerable<string> keys, bool getData)
{
string script = getData ? Const.GET_LIST_SCRIPT : Const.GET_EXPIRATION_VALUE_SCRIPT;
var arrayRedisResult = Db
.ScriptEvaluate(script, keys.Select(key => (RedisKey)key).ToArray())
.ToDictionary();
return GetListByArrayRedisResult(arrayRedisResult, getData);
}
internal async Task<List<DataCacheModel>> GetListAsync(IEnumerable<string> keys, bool getData)
{
string script = getData ? Const.GET_LIST_SCRIPT : Const.GET_EXPIRATION_VALUE_SCRIPT;
var arrayRedisResult = (await Db
.ScriptEvaluateAsync(script, keys.Select(key => (RedisKey)key).ToArray()))
.ToDictionary();
return GetListByArrayRedisResult(arrayRedisResult, getData);
}
private static List<DataCacheModel> GetListByArrayRedisResult(Dictionary<string, RedisResult> arrayRedisResult, bool getData)
{
List<DataCacheModel> list = new List<DataCacheModel>();
foreach (var redisResult in arrayRedisResult)
{
var byteArray = (RedisValue[])redisResult.Value;
list.Add(getData ? MapMetadataByAutomatic(redisResult.Key, byteArray) : MapMetadata(redisResult.Key, byteArray));
}
return list;
}
private static List<KeyValuePair<string, TimeSpan?>> GetKeyAndExpireList(
List<DataCacheModel> models,
CancellationToken token)
{
List<KeyValuePair<string, TimeSpan?>> list = new();
DateTimeOffset? creationTime = DateTimeOffset.UtcNow;
foreach (var model in models)
{
var res = model.GetExpiration(creationTime, token);
if (res.State)
{
list.Add(new KeyValuePair<string, TimeSpan?>(model.Key, res.Expire));
}
}
return list;
}
internal static DataCacheModel MapMetadata(
string key,
RedisValue[] results)
{
RedisValue data = results.Length > 2 ? results[2] : RedisValue.Null;
var absoluteExpirationTicks = (long?)results[0];
if (absoluteExpirationTicks is null or Const.DEADLINE_LASTING)
absoluteExpirationTicks = null;
var slidingExpirationTicks = (long?)results[1];
if (slidingExpirationTicks is null or Const.DEADLINE_LASTING)
slidingExpirationTicks = null;
return new DataCacheModel(key, absoluteExpirationTicks, slidingExpirationTicks, data);
}
private static DataCacheModel MapMetadataByAutomatic(string key, RedisValue[] results)
{
long? absoluteExpiration = null;
long? slidingExpiration = null;
RedisValue data = RedisValue.Null;
for (int index = 0; index < results.Length; index += 2)
{
if (results[index] == Const.ABSOLUTE_EXPIRATION_KEY)
{
var absoluteExpirationTicks = (long?)results[index + 1];
if (absoluteExpirationTicks.HasValue && absoluteExpirationTicks.Value != Const.DEADLINE_LASTING)
{
absoluteExpiration = absoluteExpirationTicks.Value;
}
}
else if (results[index] == Const.SLIDING_EXPIRATION_KEY)
{
var slidingExpirationTicks = (long?)results[index + 1];
if (slidingExpirationTicks.HasValue && slidingExpirationTicks.Value != Const.DEADLINE_LASTING)
{
slidingExpiration = slidingExpirationTicks;
}
}
else if (results[index] == Const.DATA_KEY)
{
data = results[index + 1];
}
}
return new DataCacheModel(key, absoluteExpiration, slidingExpiration, data);
}
}