Repository navigation
Expand file tree
/
Copy pathMemoryCacheManager.cs
More file actions
230 lines (197 loc) · 7.19 KB
/
Copy pathMemoryCacheManager.cs
File metadata and controls
230 lines (197 loc) · 7.19 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
using Grand.Core.Extensions;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
namespace Grand.Core.Caching
{
/// <summary>
/// Represents a manager for caching between HTTP requests (long term caching)
/// </summary>
public partial class MemoryCacheManager : ICacheManager
{
#region Fields
private readonly IMemoryCache _cache;
/// <summary>
/// Cancellation token for clear cache
/// </summary>
protected CancellationTokenSource _cancellationTokenSource;
/// <summary>
/// All keys of cache
/// </summary>
/// <remarks>Dictionary value indicating whether a key still exists in cache</remarks>
protected static readonly ConcurrentDictionary<string, bool> _allKeys;
#endregion
#region Ctor
static MemoryCacheManager()
{
_allKeys = new ConcurrentDictionary<string, bool>();
}
public MemoryCacheManager(IMemoryCache cache)
{
_cache = cache;
_cancellationTokenSource = new CancellationTokenSource();
}
#endregion
#region Utilities
/// <summary>
/// Create entry options to item of memory cache
/// </summary>
/// <param name="cacheTime">Cache time in minutes</param>
/// <returns></returns>
protected MemoryCacheEntryOptions GetMemoryCacheEntryOptions(int cacheTime)
{
var options = new MemoryCacheEntryOptions()
// add cancellation token for clear cache
.AddExpirationToken(new CancellationChangeToken(_cancellationTokenSource.Token))
//add post eviction callback
.RegisterPostEvictionCallback(PostEviction);
//set cache time
options.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(cacheTime);
return options;
}
/// <summary>
/// Add key to dictionary
/// </summary>
/// <param name="key">Key of cached item</param>
/// <returns>Itself key</returns>
protected string AddKey(string key)
{
_allKeys.TryAdd(key, true);
return key;
}
/// <summary>
/// Remove key from dictionary
/// </summary>
/// <param name="key">Key of cached item</param>
/// <returns>Itself key</returns>
protected string RemoveKey(string key)
{
TryRemoveKey(key);
return key;
}
/// <summary>
/// Try to remove a key from dictionary, or mark a key as not existing in cache
/// </summary>
/// <param name="key">Key of cached item</param>
protected void TryRemoveKey(string key)
{
//try to remove key from dictionary
if (!_allKeys.TryRemove(key, out _))
//if not possible to remove key from dictionary, then try to mark key as not existing in cache
_allKeys.TryUpdate(key, false, true);
}
/// <summary>
/// Remove all keys marked as not existing
/// </summary>
private void ClearKeys()
{
foreach (var key in _allKeys.Where(p => !p.Value).Select(p => p.Key).ToList())
{
RemoveKey(key);
}
}
/// <summary>
/// Post eviction
/// </summary>
/// <param name="key">Key of cached item</param>
/// <param name="value">Value of cached item</param>
/// <param name="reason">Eviction reason</param>
/// <param name="state">State</param>
private void PostEviction(object key, object value, EvictionReason reason, object state)
{
//if cached item just change, then nothing doing
if (reason == EvictionReason.Replaced)
return;
//try to remove all keys marked as not existing
ClearKeys();
//try to remove this key from dictionary
TryRemoveKey(key.ToString());
}
#endregion
#region Methods
/// <summary>
/// Gets or sets the value associated with the specified key.
/// </summary>
/// <typeparam name="T">Type of cached item</typeparam>
/// <param name="key">Key of cached item</param>
/// <returns>The cached value associated with the specified key</returns>
public virtual T Get<T>(string key)
{
return _cache.Get<T>(key);
}
/// <summary>
/// Gets or sets the value associated with the specified key.
/// </summary>
/// <param name="key">Key of cached item</param>
/// <returns>The cached value associated with the specified key</returns>
public virtual (T, bool) TryGetValue<T>(string key)
{
if(_cache.TryGetValue(key, out T value))
{
return (value, true);
}
return (default(T), false);
}
/// <summary>
/// Adds the specified key and object to the cache
/// </summary>
/// <param name="key">Key of cached item</param>
/// <param name="data">Value for caching</param>
/// <param name="cacheTime">Cache time in minutes</param>
public virtual void Set(string key, object data, int cacheTime)
{
if (data != null)
{
_cache.Set(AddKey(key), data, GetMemoryCacheEntryOptions(cacheTime));
}
}
/// <summary>
/// Gets a value indicating whether the value associated with the specified key is cached
/// </summary>
/// <param name="key">Key of cached item</param>
/// <returns>True if item already is in cache; otherwise false</returns>
public virtual bool IsSet(string key)
{
return _cache.TryGetValue(key, out object _);
}
/// <summary>
/// Removes the value with the specified key from the cache
/// </summary>
/// <param name="key">Key of cached item</param>
public virtual void Remove(string key)
{
_cache.Remove(RemoveKey(key));
}
/// <summary>
/// Removes items by key pattern
/// </summary>
/// <param name="pattern">String key pattern</param>
public virtual void RemoveByPattern(string pattern)
{
this.RemoveByPattern(pattern, _allKeys.Where(p => p.Value).Select(p => p.Key));
}
/// <summary>
/// Clear all cache data
/// </summary>
public virtual void Clear()
{
//send cancellation request
_cancellationTokenSource.Cancel();
//releases all resources used by this cancellation token
_cancellationTokenSource.Dispose();
//recreate cancellation token
_cancellationTokenSource = new CancellationTokenSource();
}
/// <summary>
/// Dispose cache manager
/// </summary>
public virtual void Dispose()
{
//nothing special
}
#endregion
}
}