-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUseCacheManager.cs
More file actions
96 lines (86 loc) · 3.29 KB
/
UseCacheManager.cs
File metadata and controls
96 lines (86 loc) · 3.29 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
using System;
using System.Collections.Generic;
using CacheManager.Core;
namespace EFCache.CacheManager
{
/// <summary>
/// EFCache's ICache implementation which uses CacheManager as middleware
/// </summary>
public class UseCacheManager : ICache
{
public UseCacheManager(ICacheManager<object> valuesCacheManager, ICacheManager<ISet<string>> dependenciesCacheManager)
{
_valuesCacheManager = valuesCacheManager;
_dependenciesCacheManager = dependenciesCacheManager;
}
private readonly ICacheManager<ISet<string>> _dependenciesCacheManager;
private readonly ICacheManager<object> _valuesCacheManager;
public bool GetItem(string key, out object value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _valuesCacheManager.TryGetOrAdd(key, v => default(object), out value);
}
private static CacheItem<object> CreateCacheItem(string key, object value, TimeSpan slidingExpiration,
DateTimeOffset absoluteExpiration)
{
var hasSlidingExpiration = slidingExpiration != TimeSpan.MaxValue;
var hasAbsoluteExpiration = absoluteExpiration != DateTimeOffset.MaxValue;
if (!hasAbsoluteExpiration && !hasSlidingExpiration)
{
return new CacheItem<object>(key, value);
}
if (hasSlidingExpiration)
{
return new CacheItem<object>(key, value, ExpirationMode.Sliding, slidingExpiration);
}
return new CacheItem<object>(key, value, ExpirationMode.Absolute, absoluteExpiration.Offset);
}
public void PutItem(string key, object value, IEnumerable<string> dependentEntitySets, TimeSpan slidingExpiration,
DateTimeOffset absoluteExpiration)
{
var entitySets = new HashSet<string>(dependentEntitySets);
foreach (var entitySet in entitySets)
{
_dependenciesCacheManager.AddOrUpdate(entitySet, new HashSet<string> { key },
updateValue: set =>
{
set.Add(key);
return set;
});
}
_valuesCacheManager.Add(CreateCacheItem(key, value, slidingExpiration, absoluteExpiration));
}
public void InvalidateSets(IEnumerable<string> entitySets)
{
foreach (var entitySet in entitySets)
{
if (string.IsNullOrWhiteSpace(entitySet))
{
continue;
}
InvalidateItem(entitySet);
_dependenciesCacheManager.Remove(entitySet);
}
}
public void InvalidateItem(string key)
{
var dependencyKeys = _dependenciesCacheManager.Get(key);
if (dependencyKeys == null)
{
return;
}
foreach (var dependencyKey in dependencyKeys)
{
_valuesCacheManager.Remove(dependencyKey);
}
}
public void Clear()
{
_dependenciesCacheManager.Clear();
_valuesCacheManager.Clear();
}
}
}