首页 > 代码库 > 缓存类的写法

缓存类的写法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;
using Memcached.ClientLibrary;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Threading;
using Mopon.ZY.Data;

namespace Mopon.Caching
{
public sealed class MemCacheManager : ICacheManager
{
private ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();
static MemcachedClient memcached = new MemcachedClient();
static HashSet<String> cacheKeys = new HashSet<String>();

static MemCacheManager()
{
memcached.EnableCompression = false;
}

public MemCacheManager() { }

public T Get<T>(string key)
{
if (Memcache.IsEnable)
{
try
{
return (T)memcached.Get(key);
}
catch (Exception ex)
{
ErrorLog.Write("MemCacheManager.Get<T>(" + key + ")", "[-9113]缓存服务_获取缓存项目发生异常", ex);
}
}

return default(T);
}

public void Set(string key, object data, int cacheTime)
{
if (Memcache.IsEnable)
{
try
{
if (memcached.Set(key, data, DateTime.Now.AddMinutes(cacheTime)))
{
cacheLock.EnterWriteLock();
try
{
cacheKeys.Add(key);
}
finally
{
cacheLock.ExitWriteLock();
}
}
else
{
ErrorLog.Write("MemCacheManager.Set<T>(" + key + "), [-9113]缓存服务_设置缓存项目失败.");
}
}
catch (Exception ex)
{
ErrorLog.Write("MemCacheManager.Set<T>(" + key + ")", "[-9113]缓存服务_设置缓存项目失败", ex);
}
}
}

public bool IsSet(string key)
{
if (Memcache.IsEnable)
{
try
{
return memcached.KeyExists(key);
}
catch (Exception ex)
{
ErrorLog.Write("MemCacheManager.IsSet(" + key + ")", "[-9113]缓存服务_获取缓存项目发生异常", ex);
}
}

return false;
}

public void Remove(string key)
{
if (Memcache.IsEnable)
{
try
{
if (memcached.Delete(key))
{
cacheLock.EnterWriteLock();
try
{
cacheKeys.Remove(key);
}
finally
{
cacheLock.ExitWriteLock();
}
}

}
catch (Exception ex)
{
ErrorLog.Write("MemCacheManager.IsSet(" + key + ")", "[-9113]缓存服务_移除缓存项目发生异常", ex);
}
}
}

public void RemoveByPattern(string pattern)
{
var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
var keysToRemove = new List<String>();

foreach (var item in cacheKeys)
if (regex.IsMatch(item))
keysToRemove.Add(item);

foreach (string key in keysToRemove)
{
Remove(key);
}
}

public void Clear()
{
if (Memcache.IsEnable)
{
try
{
memcached.FlushAll();

cacheLock.EnterWriteLock();
try
{
cacheKeys.Clear();
}
finally
{
cacheLock.ExitWriteLock();
}
}
catch (Exception ex)
{
ErrorLog.Write("MemCacheManager.Clear()", "[-9113]缓存服务_清空缓存所有项时发生异常", ex);
}
}
}

//静态类--静态构造函数 全局初始化的
private static class Memcache
{
static Memcache()
{
var memRespository = new LinqRepository<MemcachedConfig>();
var listResult = memRespository.FindAll(item => item.IsEnabled ?? false);

if (listResult.Count() > 0)
{
var serverList = string.Join(",", listResult.Select(ctx => ctx.ServerList).ToArray()).Trim(‘,‘);
if (string.IsNullOrEmpty(serverList))
{
ErrorLog.Write("[-9110]缓存服务_初始化缓存服务连接参数[缓存服务器地址]为空");
}
else
{
try
{
//初始化池
ErrorLog.Write("初始化缓存服务器连接开始.服务器地址列表:" + serverList.ToString());
SockIOPool pool = SockIOPool.GetInstance();
pool.SetServers(serverList.Split(‘,‘));
pool.InitConnections = 5;
pool.MinConnections = 5;
pool.MaxConnections = 500;
pool.SocketConnectTimeout = 1000;
pool.SocketTimeout = 3000;
pool.MaintenanceSleep = 30;
pool.Failover = true;
pool.Nagle = false;
pool.Initialize();
//如果连接缓存服务器失败,则后继不再连接
var fieldPool = typeof(SockIOPool).GetField("_availPool", BindingFlags.Instance | BindingFlags.NonPublic);
var availPool = fieldPool.GetValue(pool) as Hashtable;
IsEnable = availPool != null && availPool.Count > 0;

ErrorLog.Write("初始化缓存服务器连接结束");

if (!IsEnable) Shutdown();
}
catch (Exception ex)
{
ErrorLog.Write("MemcacheManage.ConnetServers()", "[-9111]缓存服务_初始化缓存服务连接发生异常", ex);
}
}
}
}

public static void Shutdown()
{
SockIOPool.GetInstance().Shutdown();
ErrorLog.Write("MemcacheManage.ColseServer()", "关闭缓存服务时间:" + DateTime.Now.ToString(), null);
}

public static Boolean IsEnable { get; private set; }
}

}
}

缓存类的写法