Repository navigation
Expand file tree
/
Copy pathDistributedRedisCache.cs
More file actions
113 lines (90 loc) · 3.27 KB
/
Copy pathDistributedRedisCache.cs
File metadata and controls
113 lines (90 loc) · 3.27 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
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using System;
namespace Grand.Core.Caching
{
public partial class DistributedRedisCache : ICacheManager
{
private readonly IDistributedCache _distributedCache;
private readonly IDistributedRedisCacheExtended _distributedRedisCacheExtended;
public DistributedRedisCache(IDistributedCache distributedCache, IDistributedRedisCacheExtended distributedRedisCacheExtended)
{
this._distributedCache = distributedCache;
this._distributedRedisCacheExtended = distributedRedisCacheExtended;
}
/// <summary>
/// Create entry options to item of redis cache
/// </summary>
/// <param name="cacheTime">Cache time in minutes</param>
/// <returns></returns>
protected DistributedCacheEntryOptions GetDistributedCacheEntryOptions(int cacheTime)
{
return new DistributedCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(cacheTime));
}
public virtual T Get<T>(string key)
{
//get serialized item from cache
var serializedItem = _distributedCache.GetString(key);
if (string.IsNullOrEmpty(serializedItem))
return default(T);
//deserialize item
var item = JsonConvert.DeserializeObject<T>(serializedItem);
if (item == null)
return default(T);
return item;
}
public virtual (T, bool) TryGetValue<T>(string key)
{
byte[] result;
try
{
result = _distributedCache.Get(key);
if (result == null)
return (default(T), false);
}
catch
{
return (default(T), false);
}
//get serialized item from cache
var serializedItem = System.Text.Encoding.Default.GetString(result);
if (string.IsNullOrEmpty(serializedItem))
return (default(T), true);
//deserialize item
var item = JsonConvert.DeserializeObject<T>(serializedItem);
if (item == null)
return (default(T), true);
return (item, true);
}
public virtual void Remove(string key)
{
_distributedCache.Remove(key);
}
public virtual void RemoveByPattern(string pattern)
{
_distributedRedisCacheExtended.RemoveByPatternAsync(pattern);
}
public virtual void Set(string key, object data, int cacheTime)
{
if (data == null)
return;
//serialize item
var serializedItem = JsonConvert.SerializeObject(data);
//and set it to cache
_distributedCache.SetString(key, serializedItem, GetDistributedCacheEntryOptions(cacheTime));
}
public bool IsSet(string key)
{
return _distributedCache.Get(key)?.Length > 0;
}
public virtual void Clear()
{
_distributedRedisCacheExtended.ClearAsync();
}
public virtual void Dispose()
{
//nothing special
}
}
}