forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryCacheClient.cs
More file actions
417 lines (362 loc) · 13.4 KB
/
MemoryCacheClient.cs
File metadata and controls
417 lines (362 loc) · 13.4 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
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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using ServiceStack.Logging;
namespace ServiceStack.Caching
{
public class MemoryCacheClient : ICacheClientExtended, IRemoveByPattern
{
private static readonly ILog Log = LogManager.GetLogger(typeof(MemoryCacheClient));
private ConcurrentDictionary<string, CacheEntry> memory;
private ConcurrentDictionary<string, int> counters;
public bool FlushOnDispose { get; set; }
private class CacheEntry
{
private object cacheValue;
/// <summary>
/// Create new instance of CacheEntry.
/// </summary>
public CacheEntry(object value, DateTime? expiresAt)
{
Value = value;
ExpiresAt = expiresAt;
LastModifiedTicks = DateTime.UtcNow.Ticks;
}
/// <summary>UTC time at which CacheEntry expires.</summary>
internal DateTime? ExpiresAt { get; set; }
internal bool HasExpired
{
get { return ExpiresAt != null && ExpiresAt < DateTime.UtcNow; }
}
internal object Value
{
get { return cacheValue; }
set
{
cacheValue = value;
LastModifiedTicks = DateTime.UtcNow.Ticks;
}
}
internal long LastModifiedTicks { get; private set; }
}
public MemoryCacheClient()
{
this.memory = new ConcurrentDictionary<string, CacheEntry>();
this.counters = new ConcurrentDictionary<string, int>();
}
private bool TryGetValue(string key, out CacheEntry entry)
{
return this.memory.TryGetValue(key, out entry);
}
private void Set(string key, CacheEntry entry)
{
this.memory[key] = entry;
}
/// <summary>
/// Stores The value with key only if such key doesn't exist at the server yet.
/// </summary>
private bool CacheAdd(string key, object value, DateTime? expiresAt = null)
{
CacheEntry entry;
if (this.TryGetValue(key, out entry)) return false;
entry = new CacheEntry(value, expiresAt);
this.Set(key, entry);
return true;
}
/// <summary>
/// Adds or replaces the value with key.
/// </summary>
private bool CacheSet(string key, object value, DateTime expiresAt)
{
return CacheSet(key, value, expiresAt, null);
}
/// <summary>
/// Adds or replaces the value with key.
/// </summary>
private bool CacheSet(string key, object value, DateTime? expiresAt = null, long? checkLastModified = null)
{
CacheEntry entry;
if (!this.TryGetValue(key, out entry))
{
entry = new CacheEntry(value, expiresAt);
this.Set(key, entry);
return true;
}
if (checkLastModified.HasValue
&& entry.LastModifiedTicks != checkLastModified.Value) return false;
entry.Value = value;
entry.ExpiresAt = expiresAt;
return true;
}
/// <summary>
/// Replace the value with specified key if it exists.
/// </summary>
private bool CacheReplace(string key, object value, DateTime? expiresAt = null)
{
return !CacheSet(key, value, expiresAt);
}
public void Dispose()
{
if (!FlushOnDispose) return;
this.memory = new ConcurrentDictionary<string, CacheEntry>();
this.counters = new ConcurrentDictionary<string, int>();
}
public bool Remove(string key)
{
CacheEntry item;
return this.memory.TryRemove(key, out item);
}
public void RemoveAll(IEnumerable<string> keys)
{
foreach (var key in keys)
{
try
{
this.Remove(key);
}
catch (Exception ex)
{
Log.Error(string.Format("Error trying to remove {0} from the cache", key), ex);
}
}
}
public object Get(string key)
{
long lastModifiedTicks;
return Get(key, out lastModifiedTicks);
}
public object Get(string key, out long lastModifiedTicks)
{
lastModifiedTicks = 0;
CacheEntry cacheEntry;
if (this.memory.TryGetValue(key, out cacheEntry))
{
if (cacheEntry.HasExpired)
{
this.memory.TryRemove(key, out cacheEntry);
return null;
}
lastModifiedTicks = cacheEntry.LastModifiedTicks;
return cacheEntry.Value;
}
return null;
}
public T Get<T>(string key)
{
var value = Get(key);
if (value != null) return (T)value;
return default(T);
}
private int UpdateCounter(string key, int value)
{
lock (counters)
{
if (!this.counters.ContainsKey(key))
{
this.counters[key] = 0;
}
this.counters[key] += value;
return this.counters[key];
}
}
public long Increment(string key, uint amount)
{
return UpdateCounter(key, (int)amount);
}
public long Decrement(string key, uint amount)
{
return UpdateCounter(key, (int)amount * -1);
}
/// <summary>
/// Add the value with key to the cache, set to never expire.
/// </summary>
public bool Add<T>(string key, T value)
{
return CacheAdd(key, value);
}
/// <summary>
/// Add or replace the value with key to the cache, set to never expire.
/// </summary>
public bool Set<T>(string key, T value)
{
return CacheSet(key, value);
}
/// <summary>
/// Replace the value with key in the cache, set to never expire.
/// </summary>
public bool Replace<T>(string key, T value)
{
return CacheReplace(key, value);
}
/// <summary>
/// Add the value with key to the cache, set to expire at specified DateTime.
/// </summary>
/// <remarks>This method examines the DateTimeKind of expiresAt to determine if conversion to
/// universal time is needed. The version of Add that takes a TimeSpan expiration is faster
/// than using this method with a DateTime of Kind other than Utc, and is not affected by
/// ambiguous local time during daylight savings/standard time transition.</remarks>
public bool Add<T>(string key, T value, DateTime expiresAt)
{
if (expiresAt.Kind != DateTimeKind.Utc) expiresAt = expiresAt.ToUniversalTime();
return CacheAdd(key, value, expiresAt);
}
/// <summary>
/// Add or replace the value with key to the cache, set to expire at specified DateTime.
/// </summary>
/// <remarks>This method examines the DateTimeKind of expiresAt to determine if conversion to
/// universal time is needed. The version of Set that takes a TimeSpan expiration is faster
/// than using this method with a DateTime of Kind other than Utc, and is not affected by
/// ambiguous local time during daylight savings/standard time transition.</remarks>
public bool Set<T>(string key, T value, DateTime expiresAt)
{
if (expiresAt.Kind != DateTimeKind.Utc) expiresAt = expiresAt.ToUniversalTime();
return CacheSet(key, value, expiresAt);
}
/// <summary>
/// Replace the value with key in the cache, set to expire at specified DateTime.
/// </summary>
/// <remarks>This method examines the DateTimeKind of expiresAt to determine if conversion to
/// universal time is needed. The version of Replace that takes a TimeSpan expiration is faster
/// than using this method with a DateTime of Kind other than Utc, and is not affected by
/// ambiguous local time during daylight savings/standard time transition.</remarks>
public bool Replace<T>(string key, T value, DateTime expiresAt)
{
if (expiresAt.Kind != DateTimeKind.Utc) expiresAt = expiresAt.ToUniversalTime();
return CacheReplace(key, value, expiresAt);
}
/// <summary>
/// Add the value with key to the cache, set to expire after specified TimeSpan.
/// </summary>
public bool Add<T>(string key, T value, TimeSpan expiresIn)
{
return CacheAdd(key, value, DateTime.UtcNow.Add(expiresIn));
}
/// <summary>
/// Add or replace the value with key to the cache, set to expire after specified TimeSpan.
/// </summary>
public bool Set<T>(string key, T value, TimeSpan expiresIn)
{
return CacheSet(key, value, DateTime.UtcNow.Add(expiresIn));
}
/// <summary>
/// Replace the value with key in the cache, set to expire after specified TimeSpan.
/// </summary>
public bool Replace<T>(string key, T value, TimeSpan expiresIn)
{
return CacheReplace(key, value, DateTime.UtcNow.Add(expiresIn));
}
public void FlushAll()
{
this.memory = new ConcurrentDictionary<string, CacheEntry>();
}
public IDictionary<string, T> GetAll<T>(IEnumerable<string> keys)
{
var valueMap = new Dictionary<string, T>();
foreach (var key in keys)
{
var value = Get<T>(key);
valueMap[key] = value;
}
return valueMap;
}
public void SetAll<T>(IDictionary<string, T> values)
{
foreach (var entry in values)
{
Set(entry.Key, entry.Value);
}
}
private static string ConvertToRegex(string pattern)
{
return pattern.Replace("*", ".*").Replace("?", ".+");
}
public void RemoveByPattern(string pattern)
{
RemoveByRegex(ConvertToRegex(pattern));
}
public void RemoveByRegex(string pattern)
{
var regex = new Regex(pattern);
var enumerator = this.memory.GetEnumerator();
var keysToRemove = new List<string>();
try
{
while (enumerator.MoveNext())
{
var current = enumerator.Current;
if (regex.IsMatch(current.Key) || current.Value.HasExpired)
{
keysToRemove.Add(current.Key);
}
}
RemoveAll(keysToRemove);
}
catch (Exception ex)
{
Log.Error(string.Format("Error trying to remove items from cache with this {0} pattern", pattern), ex);
}
}
public IEnumerable<string> GetKeysByPattern(string pattern)
{
return pattern == "*"
? memory.Keys
: GetKeysByRegex(ConvertToRegex(pattern));
}
public List<string> GetKeysByRegex(string pattern)
{
var regex = new Regex(pattern);
var enumerator = this.memory.GetEnumerator();
var keys = new List<string>();
var expiredKeys = new List<string>();
try
{
while (enumerator.MoveNext())
{
var current = enumerator.Current;
if (!regex.IsMatch(current.Key))
continue;
if (current.Value.HasExpired)
{
expiredKeys.Add(current.Key);
}
else
{
keys.Add(current.Key);
}
}
RemoveAll(expiredKeys);
}
catch (Exception ex)
{
Log.Error(string.Format("Error trying to remove items from cache with this {0} pattern", pattern), ex);
}
return keys;
}
public void RemoveExpiredEntries()
{
var expiredKeys = new List<string>();
var enumerator = this.memory.GetEnumerator();
while (enumerator.MoveNext())
{
var current = enumerator.Current;
if (current.Value.HasExpired)
{
expiredKeys.Add(current.Key);
}
}
RemoveAll(expiredKeys);
}
public TimeSpan? GetTimeToLive(string key)
{
CacheEntry cacheEntry;
if (this.memory.TryGetValue(key, out cacheEntry))
{
if (cacheEntry.ExpiresAt == null)
return TimeSpan.MaxValue;
return cacheEntry.ExpiresAt - DateTime.UtcNow;
}
return null;
}
}
}