Memcach、WebCache、MemoryCache缓存帮助类
场景说明使用方法业务层的缓存类实例化接口ICacheMgrMemcachMgr 实现WebCacheMgr 的实现MemoryCacheMgr 的实现
场景说明
项目中使用的缓存各用各的,难以统一,所以封装一下,一来方便使用,二来统一调用,以后想改用其它缓存方式也不用整个项目大改。
使用方法
CacheKey
.cache
["key"] = 123;
CacheKey
.cache
["key", 60] = 123;
CacheKey
.cache
["key", DateTime
.Now
.AddMinutes(60)] = 123;
var obj1
= CacheKey
.cache
["key"];
var obj2
= CacheKey
.cache
.GetCache<object>("key", 60, delegate { return new object(); });
var obj3
= CacheKey
.cache
.GetCache<object>("key", DateTime
.Now
.AddMinutes(60), delegate { return new object(); });
CacheKey
.cache
.Remove("key");
CacheKey
.cache
.Clear();
业务层的缓存类实例化
这里主要是让所有成员包括自己记住自己都用了什么缓存key,尽量防止被其它地方的代码通过key覆盖缓存,这种错误虽然少,但一出现就很难排查。这里用的是简单单例模式
public class CacheKey
{
public static readonly ICacheMgr cache
= new MemoryCacheMgr();
public static readonly string Cagetory
= "XSite_Cagetory_Cache";
internal static string GetXxxxKey()
{
return "XxxxKey";
}
}
接口ICacheMgr
规范化缓存封装的实现方式
public interface ICacheMgr
{
object this[string key
, int duration
] { get; set; }
object this[string key
, DateTime duration
] { get; set; }
object this[string key
] { get; set; }
bool KeyExists(string key
);
void Remove(string key
);
bool Clear();
T
GetCache<T>(string key
, DateTime expiry
, Func
<T
> action
);
T
GetCache<T>(string key
, int duration
, Func
<T
> action
);
T
GetCache<T>(string key
, T def
= default(T
));
}
MemcachMgr 实现
using Memcached
.ClientLibrary
;
public class MemcachMgr : ICacheMgr
{
private static MemcachedClient _client
;
private static readonly object LockObj
= new object();
static MemcachMgr()
{
string memcachIpAndPort
= System
.Configuration
.ConfigurationManager
.AppSettings
["MemcachIpAndPort"] ?? string.Empty
;
string memcachPoolName
= System
.Configuration
.ConfigurationManager
.AppSettings
["MemcachPoolName"] ?? string.Empty
;
string[] ipANdPorts
= memcachIpAndPort
.Split(',');
if (ipANdPorts
.Length
== 0) { throw new Exception("请在 .config 中添加 appSettings MemcachIpAndPort 的配置"); }
Initialize(ipANdPorts
, memcachPoolName
);
}
private static void Initialize(string[] serverList
, string poolName
)
{
var pool
= SockIOPool
.GetInstance(poolName
);
pool
.SetServers(serverList
);
pool
.SetWeights(new int[] { 1 });
pool
.InitConnections
= 1;
pool
.MinConnections
= 1;
pool
.MaxConnections
= 500;
pool
.MaxIdle
= 1000 * 60 * 60 * 6;
pool
.SocketConnectTimeout
= 500;
pool
.SocketTimeout
= 1000*3;
pool
.MaintenanceSleep
= 30;
pool
.Failover
= true;
pool
.Nagle
= false;
pool
.MaxBusy
= 1000 * 30;
pool
.Initialize();
lock (LockObj
)
{
if (_client
== null)
{
_client
= new MemcachedClient { PoolName
= poolName
};
}
}
}
public object this[string key
, int duration
]
{
get
{
return this[key
, default(DateTime
)];
}
set
{
this[key
, DateTime
.Now
.AddMinutes(duration
)] = value;
}
}
public object this[string key
, DateTime duration
]
{
get
{
return _client
.Get(key
);
}
set
{
if (value == null)
Remove(key
);
else
{
_client
.Set(key
, value, duration
);
}
}
}
public object this[string key
]
{
get
{
return this[key
, default(DateTime
)];
}
set
{
this[key
, DateTime
.Now
.AddMinutes(60)] = value;
}
}
public bool KeyExists(string key
)
{
return _client
.KeyExists(key
);
}
public void Remove(string key
)
{
_client
.Delete(key
);
}
public bool Clear()
{
return _client
.FlushAll();
}
public T
GetCache<T>(string key
, DateTime expiry
, Func
<T
> action
)
{
if (action
== null)
{
throw new ArgumentNullException("action");
}
object obj
= this[key
];
if (obj
== null)
{
obj
= action();
if (obj
!= null)
this[key
, expiry
] = obj
;
}
if (obj
== null) return default(T
);
return (T
)obj
;
}
public T
GetCache<T>(string key
, int duration
, Func
<T
> action
)
{
return GetCache<T>(key
, DateTime
.Now
.AddMinutes(duration
), action
);
}
public T
GetCache<T>(string key
, T def
= default(T
))
{
object obj
= this[key
];
if (obj
== null) return def
;
try
{
return (T
)obj
;
}
catch { return def
; }
}
}
WebCacheMgr 的实现
using System
.Web
.Caching
;
public partial class WebCacheMgr : ICacheMgr
{
private static volatile System.Web.Caching.Cache cache
= HttpRuntime
.Cache
;
public object this[string key
, DateTime duration
]
{
get { return this[key
, 0]; }
set
{
if (duration
== default(DateTime
) || value == null)
{
cache
.Remove(key
);
}
else
{
int dMin
= (int)(duration
- DateTime
.Now
).TotalMinutes
;
if (dMin
> 0)
{
this[key
, dMin
] = value;
}
}
}
}
public object this[string key
, int duration
]
{
get
{
object obj
= cache
.Get(key
);
return ToolX
.Clone(obj
);
}
set
{
if (null == value)
{
cache
.Remove(key
);
return;
}
int seconds
= duration
* 60;
if (seconds
<= 0)
{
cache
.Insert(key
, value, null, DateTime
.MaxValue
, System
.Web
.Caching
.Cache
.NoSlidingExpiration
, CacheItemPriority
.Default
, null);
}
else
{
cache
.Insert(key
, value, null, DateTime
.Now
.AddSeconds(seconds
), System
.Web
.Caching
.Cache
.NoSlidingExpiration
, CacheItemPriority
.Default
, null);
}
}
}
public object this[string key
]
{
get
{
return this[key
, default(DateTime
)];
}
set
{
this[key
, (60)] = value;
}
}
public bool KeyExists(string key
)
{
return cache
.Get(key
) != null;
}
public void Remove(string key
)
{
cache
.Remove(key
);
}
public bool Clear()
{
List
<string> ls
= new List<string>();
foreach (System.Collections.DictionaryEntry k
in cache
)
{
if (k
.Key
!= null)
{
ls
.Add(k
.Key
.ToString());
}
}
foreach (var k
in ls
)
{
cache
.Remove(k
);
}
return true;
}
public T
GetCache<T>(string key
, DateTime expiry
, Func
<T
> action
)
{
if (action
== null)
{
throw new ArgumentNullException("action");
}
object obj
= this[key
];
if (obj
== null)
{
obj
= action();
if (obj
!= null)
this[key
, expiry
] = obj
;
}
if (obj
== null) return default(T
);
return (T
)obj
;
}
public T
GetCache<T>(string key
, int duration
, Func
<T
> action
)
{
return GetCache<T>(key
, DateTime
.Now
.AddMinutes(duration
), action
);
}
public T
GetCache<T>(string key
, T def
= default(T
))
{
object obj
= this[key
];
if (obj
== null) return def
;
try
{
return (T
)obj
;
}
catch { return def
; }
}
}
MemoryCacheMgr 的实现
using System
.Runtime
.Caching
;
public partial class MemoryCacheMgr : ICacheMgr
{
public object this[string key
, DateTime duration
]
{
get
{
object obj
= MemoryCache
.Default
.Get(key
);
return ToolX
.Clone(obj
);
}
set
{
MemoryCache
.Default
.Set(key
, value, DateTimeOffset
.Now
.Add(duration
- DateTime
.Now
), null);
}
}
public object this[string key
, int duration
]
{
get { return this[key
, default(DateTime
)]; }
set
{
if (duration
<= 0 || value == null)
{
MemoryCache
.Default
.Remove(key
);
}
else
{
this[key
, DateTime
.Now
.AddMinutes(duration
)] = value;
}
}
}
public object this[string key
]
{
get
{
return this[key
, default(DateTime
)];
}
set
{
this[key
, (60)] = value;
}
}
public bool KeyExists(string key
)
{
return MemoryCache
.Default
.Get(key
) != null;
}
public void Remove(string key
)
{
MemoryCache
.Default
.Remove(key
);
}
public bool Clear()
{
List
<string> ls
= new List<string>();
foreach (var k
in MemoryCache
.Default
) { ls
.Add(k
.Key
); }
foreach (var k
in ls
)
{
MemoryCache
.Default
.Remove(k
);
}
return true;
}
public T
GetCache<T>(string key
, DateTime expiry
, Func
<T
> action
)
{
if (action
== null)
{
throw new ArgumentNullException("action");
}
object obj
= this[key
];
if (obj
== null)
{
obj
= action();
if (obj
!= null)
this[key
, expiry
] = obj
;
}
if (obj
== null) return default(T
);
return (T
)obj
;
}
public T
GetCache<T>(string key
, int duration
, Func
<T
> action
)
{
return GetCache<T>(key
, DateTime
.Now
.AddMinutes(duration
), action
);
}
public T
GetCache<T>(string key
, T def
= default(T
))
{
object obj
= this[key
];
if (obj
== null) return def
;
try
{
return (T
)obj
;
}
catch { return def
; }
}
}
原文链接:http://blog.albsz.cn/2020-07-03-forcache.html