-
Notifications
You must be signed in to change notification settings - Fork 0
/
CacheManager.cs
52 lines (46 loc) · 1.35 KB
/
CacheManager.cs
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
public class CacheManager : ICache, IDisposable
{
private static object _padlock = new object();
public InMemoryCache InMemoryCache { get; }
public SqlCache SqlCache { get; }
public CacheManager(string sqlConnection, int sqlSlidingExpiryTimeInSeconds, int memoryAbsoluteExpiryTimeInSeconds)
{
SqlCache = new SqlCache(sqlConnection, sqlSlidingExpiryTimeInSeconds);
InMemoryCache = new InMemoryCache(memoryAbsoluteExpiryTimeInSeconds);
}
public T Get<T>(string key)
{
return TryGetFromMemoryThenFromSource<T>(key);
}
public void Put<T>(string key, T item)
{
lock(_padlock)
{
SqlCache.Put(key, item.ToByteArray());
InMemoryCache.Put(key, item);
}
}
private T TryGetFromMemoryThenFromSource<T>(string key)
{
T cacheItem;
lock (_padlock)
{
cacheItem = InMemoryCache.Get<T>(key);
if (cacheItem == null)
{
// Key not in cache, so get data.
cacheItem = SqlCache.Get<T>(key);
if (cacheItem != null)
{
InMemoryCache.Put(key, cacheItem);
}
}
}
return cacheItem;
}
public void Dispose()
{
MemoryCache.Dispose();
SqlCache.Dispose();
}
}