forked from xuxiaowei007/FoxOne
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCacheHelper.cs
97 lines (87 loc) · 2.74 KB
/
CacheHelper.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
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Caching;
namespace FoxOne.Core
{
public static class CacheHelper
{
private static ICache cache;
private static readonly object lockKey = new object();
static CacheHelper()
{
cache = ObjectHelper.GetObject<ICache>();
}
public static IList<string> AllKeys
{
get
{
return cache.AllKeys;
}
}
public static void SetValue(string key, object value)
{
SetValue(key, value, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);
}
public static void SetValue(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration)
{
lock (lockKey)
{
Remove(key);
cache.SetValue(key, value, absoluteExpiration, slidingExpiration);
}
}
public static object GetValue(string key)
{
return cache.GetValue(key);
}
public static bool Remove(string key)
{
if (cache.GetValue(key) != null)
{
cache.Remove(key);
return true;
}
return false;
}
public static void Clean()
{
lock (lockKey)
{
foreach (var key in cache.AllKeys)
{
cache.Remove(key);
}
}
}
public static T GetFromCache<T>(string key, Func<T> fun) where T : class
{
return GetFromCache<T>(key, fun, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);
}
public static T GetFromCache<T>(string key, Func<T> fun, DateTime absoluteExpiration, TimeSpan slidingExpiration) where T : class
{
T returnValue = GetValue(key) as T;
if (returnValue == null)
{
lock (lockKey)
{
returnValue = GetValue(key) as T;
if (returnValue == null)
{
returnValue = fun();
if (returnValue != null && !string.IsNullOrEmpty(returnValue.ToString()))
{
cache.SetValue(key, returnValue, absoluteExpiration, slidingExpiration);
}
}
}
}
else
{
Logger.Debug("cache hit with key:{0}", key);
}
return returnValue;
}
}
}