-
Notifications
You must be signed in to change notification settings - Fork 2
/
Cache.Redis.Extensions.cs
674 lines (622 loc) · 26.8 KB
/
Cache.Redis.Extensions.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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
#region Related components
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
using CacheUtils;
#endregion
namespace net.vieapps.Components.Caching
{
public static class RedisCachingExtensions
{
internal static bool Set(this IDatabase redis, string key, byte[] value, TimeSpan validFor)
=> !string.IsNullOrWhiteSpace(key) && redis.StringSet(key, value, validFor);
/// <summary>
/// Adds an item into cache with a specified key (if the key is already existed, then old cached item will be overriden)
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="validFor"></param>
/// <returns></returns>
public static bool Set(this IDatabase redis, string key, object value, TimeSpan validFor)
=> !string.IsNullOrWhiteSpace(key) && redis.Set(key, Helper.Serialize(value), validFor);
/// <summary>
/// Adds an item into cache with a specified key (if the key is already existed, then old cached item will be overriden)
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expiresAt"></param>
/// <returns></returns>
public static bool Set(this IDatabase redis, string key, object value, DateTime expiresAt)
=> redis.Set(key, value, expiresAt.ToTimeSpan());
/// <summary>
/// Adds an item into cache with a specified key (if the key is already existed, then old cached item will be overriden)
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expirationTime"></param>
/// <returns></returns>
public static bool Set(this IDatabase redis, string key, object value, int expirationTime = 0)
=> redis.Set(key, value, expirationTime > 0 ? TimeSpan.FromMinutes(expirationTime) : TimeSpan.Zero);
internal static Task<bool> SetAsync(this IDatabase redis, string key, byte[] value, TimeSpan validFor, CancellationToken cancellationToken = default)
=> string.IsNullOrWhiteSpace(key)
? Task.FromResult(false)
: redis.StringSetAsync(key, value, validFor).WithCancellationToken(cancellationToken);
/// <summary>
/// Adds an item into cache with a specified key (if the key is already existed, then old cached item will be overriden)
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="validFor"></param>
/// <returns></returns>
public static Task<bool> SetAsync(this IDatabase redis, string key, object value, TimeSpan validFor, CancellationToken cancellationToken = default)
=> string.IsNullOrWhiteSpace(key)
? Task.FromResult(false)
: redis.SetAsync(key, Helper.Serialize(value), validFor, cancellationToken);
/// <summary>
/// Adds an item into cache with a specified key (if the key is already existed, then old cached item will be overriden)
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expiresAt"></param>
/// <returns></returns>
public static Task<bool> SetAsync(this IDatabase redis, string key, object value, DateTime expiresAt, CancellationToken cancellationToken = default)
=> redis.SetAsync(key, value, expiresAt.ToTimeSpan(), cancellationToken);
/// <summary>
/// Adds an item into cache with a specified key (if the key is already existed, then old cached item will be overriden)
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expirationTime"></param>
/// <returns></returns>
public static Task<bool> SetAsync(this IDatabase redis, string key, object value, int expirationTime = 0, CancellationToken cancellationToken = default)
=> redis.SetAsync(key, value, expirationTime > 0 ? TimeSpan.FromMinutes(expirationTime) : TimeSpan.Zero, cancellationToken);
/// <summary>
/// Adds an item into cache with a specified key (if the key is already existed, then old cached item will be overriden)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="redis"></param>
/// <param name="items"></param>
/// <param name="validFor"></param>
public static void Set<T>(this IDatabase redis, IDictionary<string, T> items, TimeSpan validFor)
=> items?.Where(kvp => !string.IsNullOrWhiteSpace(kvp.Key)).ToList().ForEach(kvp => redis.StringSet(kvp.Key, Helper.Serialize(kvp.Value), validFor));
/// <summary>
/// Adds an item into cache with a specified key (if the key is already existed, then old cached item will be overriden)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="redis"></param>
/// <param name="items"></param>
/// <param name="validFor"></param>
/// <returns></returns>
public static Task SetAsync<T>(this IDatabase redis, IDictionary<string, T> items, TimeSpan validFor, CancellationToken cancellationToken = default)
=> Task.WhenAll(items?.Where(kvp => !string.IsNullOrWhiteSpace(kvp.Key)).Select(kvp => redis.StringSetAsync(kvp.Key, Helper.Serialize(kvp.Value), validFor).WithCancellationToken(cancellationToken)) ?? new List<Task<bool>>());
internal static void Set(this IDatabase redis, IDictionary<string, byte[]> items, TimeSpan validFor)
=> items?.Where(kvp => !string.IsNullOrWhiteSpace(kvp.Key)).ToList().ForEach(kvp => redis.StringSet(kvp.Key, kvp.Value, validFor));
internal static Task SetAsync(this IDatabase redis, IDictionary<string, byte[]> items, TimeSpan validFor, CancellationToken cancellationToken = default)
=> Task.WhenAll(items?.Where(kvp => !string.IsNullOrWhiteSpace(kvp.Key)).Select(kvp => redis.StringSetAsync(kvp.Key, kvp.Value, validFor).WithCancellationToken(cancellationToken)) ?? new List<Task<bool>>());
/// <summary>
/// Adds an item into cache with a specified key when the the key is not existed
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="validFor"></param>
/// <returns></returns>
public static bool Add(this IDatabase redis, string key, object value, TimeSpan validFor)
=> !string.IsNullOrWhiteSpace(key) && !redis.Exists(key) && redis.Set(key, value, validFor);
/// <summary>
/// Adds an item into cache with a specified key when the the key is not existed
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expiresAt"></param>
/// <returns></returns>
public static bool Add(this IDatabase redis, string key, object value, DateTime expiresAt)
=> redis.Add(key, value, expiresAt.ToTimeSpan());
/// <summary>
/// Adds an item into cache with a specified key when the the key is not existed
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expirationTime"></param>
/// <returns></returns>
public static bool Add(this IDatabase redis, string key, object value, int expirationTime = 0)
=> redis.Add(key, value, expirationTime > 0 ? TimeSpan.FromMinutes(expirationTime) : TimeSpan.Zero);
/// <summary>
/// Adds an item into cache with a specified key when the the key is not existed
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="validFor"></param>
/// <returns></returns>
public static async Task<bool> AddAsync(this IDatabase redis, string key, object value, TimeSpan validFor, CancellationToken cancellationToken = default)
=> !string.IsNullOrWhiteSpace(key) && !await redis.ExistsAsync(key, cancellationToken).ConfigureAwait(false) && await redis.SetAsync(key, value, validFor, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Adds an item into cache with a specified key when the the key is not existed
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expiresAt"></param>
/// <returns></returns>
public static Task<bool> AddAsync(this IDatabase redis, string key, object value, DateTime expiresAt, CancellationToken cancellationToken = default)
=> redis.AddAsync(key, value, expiresAt.ToTimeSpan(), cancellationToken);
/// <summary>
/// Adds an item into cache with a specified key when the the key is not existed
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expirationTime"></param>
/// <returns></returns>
public static Task<bool> AddAsync(this IDatabase redis, string key, object value, int expirationTime = 0, CancellationToken cancellationToken = default)
=> redis.AddAsync(key, value, expirationTime > 0 ? TimeSpan.FromMinutes(expirationTime) : TimeSpan.Zero, cancellationToken);
/// <summary>
/// Adds an item into cache with a specified key when the the key is existed (means update existed item)
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="validFor"></param>
/// <returns></returns>
public static bool Replace(this IDatabase redis, string key, object value, TimeSpan validFor)
=> !string.IsNullOrWhiteSpace(key) && redis.Exists(key) && redis.Set(key, value, validFor);
/// <summary>
/// Adds an item into cache with a specified key when the the key is existed (means update existed item)
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expiresAt"></param>
/// <returns></returns>
public static bool Replace(this IDatabase redis, string key, object value, DateTime expiresAt)
=> redis.Replace(key, value, expiresAt.ToTimeSpan());
/// <summary>
/// Adds an item into cache with a specified key when the the key is existed (means update existed item)
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expirationTime"></param>
/// <returns></returns>
public static bool Replace(this IDatabase redis, string key, object value, int expirationTime = 0)
=> redis.Replace(key, value, expirationTime > 0 ? TimeSpan.FromMinutes(expirationTime) : TimeSpan.Zero);
/// <summary>
/// Adds an item into cache with a specified key when the the key is existed (means update existed item)
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="validFor"></param>
/// <returns></returns>
public static async Task<bool> ReplaceAsync(this IDatabase redis, string key, object value, TimeSpan validFor, CancellationToken cancellationToken = default)
=> !string.IsNullOrWhiteSpace(key) && await redis.ExistsAsync(key, cancellationToken).ConfigureAwait(false) && await redis.SetAsync(key, value, validFor, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Adds an item into cache with a specified key when the the key is existed (means update existed item)
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expiresAt"></param>
/// <returns></returns>
public static Task<bool> ReplaceAsync(this IDatabase redis, string key, object value, DateTime expiresAt, CancellationToken cancellationToken = default)
=> redis.ReplaceAsync(key, value, expiresAt.ToTimeSpan(), cancellationToken);
/// <summary>
/// Adds an item into cache with a specified key when the the key is existed (means update existed item)
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expirationTime"></param>
/// <returns></returns>
public static Task<bool> ReplaceAsync(this IDatabase redis, string key, object value, int expirationTime = 0, CancellationToken cancellationToken = default)
=> redis.ReplaceAsync(key, value, expirationTime > 0 ? TimeSpan.FromMinutes(expirationTime) : TimeSpan.Zero, cancellationToken);
internal static object Get(this IDatabase redis, string key, bool doDeserialize)
{
var value = !string.IsNullOrWhiteSpace(key)
? (byte[])redis.StringGet(key)
: null;
return value != null && doDeserialize
? Helper.Deserialize(value)
: value;
}
/// <summary>
/// Retreives a cached item
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <returns></returns>
public static object Get(this IDatabase redis, string key)
=> redis.Get(key, true);
internal static async Task<object> GetAsync(this IDatabase redis, string key, bool doDeserialize, CancellationToken cancellationToken = default)
{
var value = !string.IsNullOrWhiteSpace(key)
? (byte[])await redis.StringGetAsync(key).WithCancellationToken(cancellationToken).ConfigureAwait(false)
: null;
return value != null && doDeserialize
? Helper.Deserialize(value)
: value;
}
/// <summary>
/// Retreives a cached item
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <returns></returns>
public static Task<object> GetAsync(this IDatabase redis, string key, CancellationToken cancellationToken = default)
=> redis.GetAsync(key, true, cancellationToken);
/// <summary>
/// Retreives a cached item
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <returns></returns>
public static T Get<T>(this IDatabase redis, string key)
{
var value = !string.IsNullOrWhiteSpace(key)
? (byte[])redis.StringGet(key)
: null;
return value != null
? Helper.Deserialize<T>(value)
: default;
}
/// <summary>
/// Retreives a cached item
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <returns></returns>
public static async Task<T> GetAsync<T>(this IDatabase redis, string key, CancellationToken cancellationToken = default)
{
var value = !string.IsNullOrWhiteSpace(key)
? (byte[])await redis.StringGetAsync(key).WithCancellationToken(cancellationToken).ConfigureAwait(false)
: null;
return value != null
? Helper.Deserialize<T>(value)
: default;
}
internal static IDictionary<string, object> Get(this IDatabase redis, IEnumerable<string> keys, bool doDeserialize)
{
var objects = new Dictionary<string, object>();
if (keys != null)
{
var redisKeys = keys.Where(key => !string.IsNullOrWhiteSpace(key)).Select(key => (RedisKey)key).ToArray();
var redisValues = redis.StringGet(redisKeys);
for (var index = 0; index < redisKeys.Length; index++)
objects[redisKeys[index]] = redisValues[index].IsNull
? null
: doDeserialize
? Helper.Deserialize(redisValues[index])
: (byte[])redisValues[index];
}
return objects;
}
/// <summary>
/// Retreives a collection of cached items
/// </summary>
/// <param name="redis"></param>
/// <param name="keys"></param>
/// <returns></returns>
public static IDictionary<string, object> Get(this IDatabase redis, IEnumerable<string> keys)
=> redis.Get(keys, true);
internal static async Task<IDictionary<string, object>> GetAsync(this IDatabase redis, IEnumerable<string> keys, bool doDeserialize, CancellationToken cancellationToken = default)
{
var objects = new Dictionary<string, object>();
if (keys != null)
{
var redisKeys = keys.Where(key => !string.IsNullOrWhiteSpace(key)).Select(key => (RedisKey)key).ToArray();
var redisValues = await redis.StringGetAsync(redisKeys).WithCancellationToken(cancellationToken).ConfigureAwait(false);
for (var index = 0; index < redisKeys.Length; index++)
objects[redisKeys[index]] = redisValues[index].IsNull
? null
: doDeserialize
? Helper.Deserialize(redisValues[index])
: (byte[])redisValues[index];
}
return objects;
}
/// <summary>
/// Retreives a collection of cached items
/// </summary>
/// <param name="redis"></param>
/// <param name="keys"></param>
/// <returns></returns>
public static Task<IDictionary<string, object>> GetAsync(this IDatabase redis, IEnumerable<string> keys, CancellationToken cancellationToken = default)
=> redis.GetAsync(keys, true, cancellationToken);
/// <summary>
/// Retreives a collection of cached items
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="redis"></param>
/// <param name="keys"></param>
/// <returns></returns>
public static IDictionary<string, T> Get<T>(this IDatabase redis, IEnumerable<string> keys)
{
var objects = new Dictionary<string, T>();
if (keys != null)
{
var redisKeys = keys.Where(key => !string.IsNullOrWhiteSpace(key)).Select(key => (RedisKey)key).ToArray();
var redisValues = redis.StringGet(redisKeys);
for (var index = 0; index < redisKeys.Length; index++)
objects[redisKeys[index]] = redisValues[index].IsNull
? default
: Helper.Deserialize<T>(redisValues[index]);
}
return objects;
}
/// <summary>
/// Retreives a collection of cached items
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="redis"></param>
/// <param name="keys"></param>
/// <returns></returns>
public static async Task<IDictionary<string, T>> GetAsync<T>(this IDatabase redis, IEnumerable<string> keys, CancellationToken cancellationToken = default)
{
var objects = new Dictionary<string, T>();
if (keys != null)
{
var redisKeys = keys.Where(key => !string.IsNullOrWhiteSpace(key)).Select(key => (RedisKey)key).ToArray();
var redisValues = await redis.StringGetAsync(redisKeys).WithCancellationToken(cancellationToken).ConfigureAwait(false);
for (var index = 0; index < redisKeys.Length; index++)
objects[redisKeys[index]] = redisValues[index].IsNull
? default
: Helper.Deserialize<T>(redisValues[index]);
}
return objects;
}
/// <summary>
/// Determines whether an item exists in the cache
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <returns></returns>
public static bool Exists(this IDatabase redis, string key)
=> !string.IsNullOrWhiteSpace(key) && redis.KeyExists(key);
/// <summary>
/// Determines whether an item exists in the cache
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <returns></returns>
public static Task<bool> ExistsAsync(this IDatabase redis, string key, CancellationToken cancellationToken = default)
=> string.IsNullOrWhiteSpace(key)
? Task.FromResult(false)
: redis.KeyExistsAsync(key).WithCancellationToken(cancellationToken);
/// <summary>
/// Removes a cached item
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <returns></returns>
public static bool Remove(this IDatabase redis, string key)
=> !string.IsNullOrWhiteSpace(key) && redis.KeyDelete(key);
/// <summary>
/// Removes a collection of cached items
/// </summary>
/// <param name="redis"></param>
/// <param name="keys"></param>
public static void Remove(this IDatabase redis, IEnumerable<string> keys)
=> redis.KeyDelete(keys?.Select(key => (RedisKey)key).ToArray());
/// <summary>
/// Removes a cached item
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <returns></returns>
public static Task<bool> RemoveAsync(this IDatabase redis, string key, CancellationToken cancellationToken = default)
=> string.IsNullOrWhiteSpace(key)
? Task.FromResult(false)
: redis.KeyDeleteAsync(key).WithCancellationToken(cancellationToken);
/// <summary>
/// Removes a collection of cached items
/// </summary>
/// <param name="redis"></param>
/// <param name="keys"></param>
public static Task RemoveAsync(this IDatabase redis, IEnumerable<string> keys, CancellationToken cancellationToken = default)
=> redis.KeyDeleteAsync(keys?.Select(key => (RedisKey)key).ToArray()).WithCancellationToken(cancellationToken);
/// <summary>
/// Updates the 'Set' member
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool UpdateSetMember(this IDatabase redis, string key, string value)
=> redis.UpdateSetMember(key, new[] { value });
/// <summary>
/// Updates the 'Set' member
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="values"></param>
/// <returns></returns>
public static bool UpdateSetMember(this IDatabase redis, string key, IEnumerable<string> values)
{
var redisValues = values?.Select(value => (RedisValue)value).ToArray();
if (!string.IsNullOrWhiteSpace(key) && values != null && values.Any())
try
{
return redis.SetAdd(key, redisValues) > 0;
}
catch (RedisServerException ex)
{
if (ex.Message.Contains("WRONGTYPE"))
{
redis.KeyDelete(key);
return redis.SetAdd(key, redisValues) > 0;
}
if (Helper.Logger.IsEnabled(LogLevel.Debug))
Helper.Logger.LogError(ex, $"Error occurred while updating a set into Redis => {ex.Message}");
throw;
}
catch (Exception ex)
{
if (Helper.Logger.IsEnabled(LogLevel.Debug))
Helper.Logger.LogError(ex, $"Error occurred while updating a set into Redis => {ex.Message}");
throw;
}
return false;
}
/// <summary>
/// Updates the 'Set' member
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task<bool> UpdateSetMemberAsync(this IDatabase redis, string key, string value, CancellationToken cancellationToken = default)
=> redis.UpdateSetMembersAsync(key, new[] { value }, cancellationToken);
/// <summary>
/// Updates the 'Set' member
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="values"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task<bool> UpdateSetMembersAsync(this IDatabase redis, string key, IEnumerable<string> values, CancellationToken cancellationToken = default)
{
var redisValues = values?.Select(value => (RedisValue)value).ToArray();
if (!string.IsNullOrWhiteSpace(key) && values != null && values.Any())
try
{
return await redis.SetAddAsync(key, redisValues).WithCancellationToken(cancellationToken).ConfigureAwait(false) > 0;
}
catch (RedisServerException ex)
{
if (ex.Message.Contains("WRONGTYPE"))
{
await redis.KeyDeleteAsync(key).WithCancellationToken(cancellationToken).ConfigureAwait(false);
return await redis.SetAddAsync(key, redisValues).WithCancellationToken(cancellationToken).ConfigureAwait(false) > 0;
}
if (Helper.Logger.IsEnabled(LogLevel.Debug))
Helper.Logger.LogError(ex, $"Error occurred while updating a set into Redis => {ex.Message}");
throw;
}
catch (Exception ex)
{
if (Helper.Logger.IsEnabled(LogLevel.Debug))
Helper.Logger.LogError(ex, $"Error occurred while updating a set into Redis => {ex.Message}");
throw;
}
return false;
}
/// <summary>
/// Removes the 'Set' member
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool DeleteSetMember(this IDatabase redis, string key, string value)
=> redis.DeleteSetMembers(key, new[] { value });
/// <summary>
/// Removes the 'Set' members
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="values"></param>
/// <returns></returns>
public static bool DeleteSetMembers(this IDatabase redis, string key, IEnumerable<string> values)
{
try
{
return redis.SetRemove(key, values?.Select(value => (RedisValue)value).ToArray()) > 0;
}
catch (Exception ex)
{
if (Helper.Logger.IsEnabled(LogLevel.Debug))
Helper.Logger.LogError(ex, $"Error occurred while updating a set from Redis => {ex.Message}");
return false;
}
}
/// <summary>
/// Removes the 'Set' member
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task<bool> DeleteSetMemberAsync(this IDatabase redis, string key, string value, CancellationToken cancellationToken = default)
=> redis.DeleteSetMembersAsync(key, new[] { value }, cancellationToken);
/// <summary>
/// Removes the 'Set' members
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="values"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task<bool> DeleteSetMembersAsync(this IDatabase redis, string key, IEnumerable<string> values, CancellationToken cancellationToken = default)
{
try
{
return await redis.SetRemoveAsync(key, values?.Select(value => (RedisValue)value).ToArray()).WithCancellationToken(cancellationToken).ConfigureAwait(false) > 0;
}
catch (Exception ex)
{
if (Helper.Logger.IsEnabled(LogLevel.Debug))
Helper.Logger.LogError(ex, $"Error occurred while updating a set from Redis => {ex.Message}");
return false;
}
}
/// <summary>
/// Gets the 'Set' member
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <returns></returns>
public static HashSet<string> FetchSetMembers(this IDatabase redis, string key)
{
try
{
var values = redis.SetMembers(key);
return new HashSet<string>(values?.Where(value => !value.IsNull).Select(value => value.ToString()) ?? Array.Empty<string>());
}
catch (Exception ex)
{
if (Helper.Logger.IsEnabled(LogLevel.Debug))
Helper.Logger.LogError(ex, $"Error occurred while getting set keys from Redis => {ex.Message}");
return new HashSet<string>();
}
}
/// <summary>
/// Gets the 'Set' member
/// </summary>
/// <param name="redis"></param>
/// <param name="key"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task<HashSet<string>> FetchSetMembersAsync(this IDatabase redis, string key, CancellationToken cancellationToken = default)
{
try
{
var values = await redis.SetMembersAsync(key).WithCancellationToken(cancellationToken).ConfigureAwait(false);
return new HashSet<string>(values?.Where(value => !value.IsNull).Select(value => value.ToString()) ?? Array.Empty<string>());
}
catch (Exception ex)
{
if (Helper.Logger.IsEnabled(LogLevel.Debug))
Helper.Logger.LogError(ex, $"Error occurred while getting a set from Redis => {ex.Message}");
return new HashSet<string>();
}
}
}
}