Repository navigation
Expand file tree
/
Copy pathRedisStorage.cs
More file actions
376 lines (311 loc) · 10.8 KB
/
Copy pathRedisStorage.cs
File metadata and controls
376 lines (311 loc) · 10.8 KB
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NetCoreStack.Jobs
{
internal class RedisStorage : IJobStorage
{
private const string SetScript = (@"
redis.call('HMSET', KEYS[1], 'type', ARGV[1], 'data', ARGV[2])
return 1");
private const string HmGetScript = (@"return redis.call('HMGET', KEYS[1], unpack(ARGV))");
private const string DelScript = (@"return redis.call('del', unpack(redis.call('keys', ARGV[1])))");
private volatile ConnectionMultiplexer _connection;
private IDatabase _redisDatabase;
private const string DataKey = "data";
private const string TypeKey = "type";
private readonly RedisStorageOptions _options;
private readonly string _instance;
private static readonly ConcurrentDictionary<string, Assembly> _cache = new ConcurrentDictionary<string, Assembly>();
private readonly SemaphoreSlim _connectionLock = new SemaphoreSlim(initialCount: 1, maxCount: 1);
protected List<Assembly> AssemblyList { get; }
public RedisStorage(IOptions<RedisStorageOptions> optionsAccessor, AssemblyOptions assemblyOptions)
{
if (optionsAccessor == null)
{
throw new ArgumentNullException(nameof(optionsAccessor));
}
if (assemblyOptions == null)
{
throw new ArgumentNullException(nameof(assemblyOptions));
}
_options = optionsAccessor.Value;
if (string.IsNullOrEmpty(_options.InstanceName))
{
throw new ArgumentNullException(nameof(_options.InstanceName));
}
_instance = _options.InstanceName + ":";
AssemblyList = assemblyOptions.AssemblyList;
}
private Type TryGetType(string fullname)
{
if(_cache.TryGetValue(fullname, out Assembly assembly))
{
return assembly.GetType(fullname, false);
}
foreach (var item in AssemblyList)
{
Type type = item.GetType(fullname, false);
if (type != null)
{
if (!_cache.ContainsKey(fullname))
{
_cache.TryAdd(fullname, item);
}
return type;
}
}
throw new ArgumentOutOfRangeException(fullname);
}
private RedisValue[] GetRedisMembers(params string[] members)
{
var redisMembers = new RedisValue[members.Length];
for (int i = 0; i < members.Length; i++)
{
redisMembers[i] = (RedisValue)members[i];
}
return redisMembers;
}
private RedisValue[] HashMemberGet(string key, params string[] members)
{
var result = _redisDatabase.ScriptEvaluate(
HmGetScript,
new RedisKey[] { key },
GetRedisMembers(members));
return (RedisValue[])result;
}
private async Task<RedisValue[]> HashMemberGetAsync(string key, params string[] members)
{
var result = await _redisDatabase.ScriptEvaluateAsync(
HmGetScript,
new RedisKey[] { key },
GetRedisMembers(members));
return (RedisValue[])result;
}
public StorageResult Get(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
Connect();
RedisValue[] results = HashMemberGet(key, TypeKey, DataKey);
if (results.Length >= 2 && results[1].HasValue)
{
return new StorageResult
{
Type = results[0],
Data = results[1]
};
}
return null;
}
public async Task<StorageResult> GetAsync(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
await ConnectAsync();
RedisValue[] results = await HashMemberGetAsync(_instance + key, TypeKey, DataKey);
if (results.Length >= 2 && results[1].HasValue)
{
return new StorageResult
{
Type = results[0],
Data = results[1]
};
}
return null;
}
public void Set(string key, object instance)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
Connect();
byte[] value = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(instance));
var result = _redisDatabase.ScriptEvaluate(SetScript, new RedisKey[] { _instance + key },
new RedisValue[]
{
instance.GetType().FullName,
value
});
}
public async Task SetAsync(string key, object instance)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
await ConnectAsync();
byte[] value = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(instance));
await _redisDatabase.ScriptEvaluateAsync(SetScript, new RedisKey[] { _instance + key },
new RedisValue[]
{
instance.GetType().FullName,
value
});
}
private void Connect()
{
if (_connection != null)
{
return;
}
_connectionLock.Wait();
try
{
if (_connection == null)
{
_connection = ConnectionMultiplexer.Connect(_options.Configuration);
_redisDatabase = _connection.GetDatabase();
}
}
finally
{
_connectionLock.Release();
}
}
private async Task ConnectAsync()
{
if (_connection != null)
{
return;
}
await _connectionLock.WaitAsync();
try
{
if (_connection == null)
{
_connection = await ConnectionMultiplexer.ConnectAsync(_options.Configuration);
_redisDatabase = _connection.GetDatabase();
}
}
finally
{
_connectionLock.Release();
}
}
public void Remove(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
Connect();
_redisDatabase.KeyDelete(_instance + key);
}
public async Task RemoveAsync(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
await ConnectAsync();
await _redisDatabase.KeyDeleteAsync(_instance + key);
}
public async Task RemoveKeysAsync(IEnumerable<IJob> jobs)
{
if (jobs != null && jobs.Any())
{
foreach (var item in jobs)
{
await RemoveAsync(item.Id);
}
}
}
public async Task RemoveAllKeysAsync()
{
await ConnectAsync();
var list = new List<string>();
await _redisDatabase.ScriptEvaluateAsync(DelScript, values: new RedisValue[] { _instance + "*" });
}
public async Task<List<string>> GetAllKeysAsync()
{
Connect();
var list = new List<string>();
var keysScript = @"return redis.call('KEYS', ARGV[1])";
var result = await _redisDatabase.ScriptEvaluateAsync(keysScript, values: new RedisValue[] { _instance + "*" });
if (result.IsNull)
return list;
try
{
var values = (RedisValue[])result;
return values.Select(p => (string)p).ToList();
}
catch (Exception)
{
}
return list;
}
public async Task<List<IJob>> GetJobsAsync()
{
List<IJob> jobs = new List<IJob>();
var keys = await GetAllKeysAsync();
if (keys != null && keys.Any())
{
foreach (var key in keys)
{
StorageResult redisResult = Get(key);
if (redisResult != null)
{
var type = TryGetType(redisResult.Type);
var job = (IJob)JsonConvert.DeserializeObject((string)redisResult.Data, type);
jobs.Add(job);
}
}
}
return jobs;
}
public async Task<List<T>> GetTypedJobsAsync<T>() where T : IJob
{
List<T> jobs = new List<T>();
var keys = await GetAllKeysAsync();
if (keys != null && keys.Any())
{
var assembly = typeof(T).Assembly;
foreach (var key in keys)
{
StorageResult redisResult = Get(key);
if (redisResult != null)
{
var fullname = redisResult.Type;
var typedEvent = typeof(T).FullName;
if (fullname == typedEvent)
{
var type = assembly.GetType(redisResult.Type, false);
var job = (T)JsonConvert.DeserializeObject((string)redisResult.Data, type);
jobs.Add(job);
}
}
}
}
return jobs;
}
public void Dispose()
{
if (_connection != null)
{
_connection.Close();
}
}
}
}