-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDistributedCacheExtensions.cs
More file actions
62 lines (53 loc) · 1.73 KB
/
DistributedCacheExtensions.cs
File metadata and controls
62 lines (53 loc) · 1.73 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
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
namespace DistributedCache.Extensions;
public static class DistributedCacheExtensions
{
public static async Task<T?> GetDataAsync<T>(this IDistributedCache cache, string cacheKey)
{
var data = await cache.GetStringAsync(cacheKey);
if (data != null)
{
var cachedData = JsonSerializer.Deserialize<T>(data);
return cachedData;
}
return default(T);
}
public static async Task SetDataAsync<T>(
this IDistributedCache cache,
string cacheKey,
T value,
TimeSpan? absoluteExpiration = null,
TimeSpan? slidingExpiration = null
)
{
var data = JsonSerializer.Serialize(value);
var options = new DistributedCacheEntryOptions();
if (slidingExpiration.HasValue)
{
options.SetSlidingExpiration(slidingExpiration.Value);
}
if (absoluteExpiration.HasValue)
{
options.SetAbsoluteExpiration(absoluteExpiration.Value);
}
await cache.SetStringAsync(cacheKey, data, options);
}
public static async Task<T?> GetOrCreateAsync<T>(
this IDistributedCache cache,
string cacheKey,
Func<Task<T>> createFunc,
TimeSpan? absoluteExpiration = null,
TimeSpan? slidingExpiration = null
)
{
var cachedData = await cache.GetDataAsync<T>(cacheKey);
if (!EqualityComparer<T>.Default.Equals(cachedData, default(T)))
{
return cachedData;
}
var newData = await createFunc();
await cache.SetDataAsync(cacheKey, newData, absoluteExpiration, slidingExpiration);
return newData;
}
}