public class huancun
{
//缓存容器
private static Dictionary<string, object> CacheDictionary = new Dictionary<string, object>();
/// <summary>
/// 添加缓存
/// </summary>
public static void Add(string key, object value)
{
CacheDictionary.Add(key, value);
SetCacheDateTime(key, value,20);
}
/// <summary>
/// 获取缓存
/// </summary>
public static T Get<T>(string key)
{
return (T)CacheDictionary[key];
}
/// <summary>
/// 判断缓存是否存在
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool Exsits(string key)
{
return CacheDictionary.ContainsKey(key);
}
/// <summary>
/// 缓存获取方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">缓存字典容器对应key</param>
/// <param name="func">委托方法 传入操作对象</param>
/// <returns></returns>
public static T GetCache<T>(string key, Func<T> func)
{
T t = default(T);
if (huancun.Exsits(key))
{
//缓存存在,直接获取原数据
t = huancun.Get<T>(key);
}
else
{
//缓存不存在,去生成缓存,并加入容器
t = func.Invoke();
huancun.Add(key, t);
}
return t;
}
/// <summary>
/// 设定绝对的过期时间
/// </summary>
/// <param name="CacheKey"></param>
/// <param name="objObject"></param>
/// <param name="seconds">超过多少秒后过期</param>
public static void SetCacheDateTime(string CacheKey, object objObject, long Seconds)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject, null, System.DateTime.Now.AddSeconds(Seconds), TimeSpan.Zero);
}
}
public class DataSource
{
/// <summary>
/// 模拟从数据库读取数据
/// 耗时、耗CPU
/// </summary>
/// <param name="count"></param>
public static int GetDataByDB(int count)
{
Console.WriteLine("-------GetDataByDB-------");
int result = 0;
for (int i = count; i < 99999999; i++)
{
result += i;
}
Thread.Sleep(2000);
return result;
}
}
///
///缓存帮助类
public class CacheHelp
{
/// <summary>
/// 缓存指定对象,设置缓存
/// </summary>
/// <param name="key">缓存的key</param>
/// <param name="value">缓存的值</param>
/// <param name="Seconds">设置缓存时间;单位:秒</param>
/// <returns></returns>
public static bool Set(string key, object value, double Seconds)
{
return Set(key, value, null, DateTime.Now.AddSeconds(Seconds), Cache.NoSlidingExpiration,
CacheItemPriority.Default, null);
}
/// <summary>
/// 缓存指定对象,设置缓存
/// </summary>
public static bool Set(string key, object value, string path)
{
try
{
var cacheDependency = new CacheDependency(path);
return Set(key, value, cacheDependency);
}
catch
{
return false;
}
}
/// <summary>
/// 缓存指定对象,设置缓存
/// </summary>
public static bool Set(string key, object value, CacheDependency cacheDependency)
{
return Set(key, value, cacheDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
CacheItemPriority.Default, null);
}
/// <summary>
/// 缓存指定对象,设置缓存
/// </summary>
public static bool Set(string key, object value, double seconds, bool isAbsulute)
{
return Set(key, value, null, (isAbsulute ? DateTime.Now.AddSeconds(seconds) : Cache.NoAbsoluteExpiration),
(isAbsulute ? Cache.NoSlidingExpiration : TimeSpan.FromSeconds(seconds)), CacheItemPriority.Default,
null);
}
/// <summary>
/// 获取缓存对象
/// </summary>
public static object Get(string key)
{
return GetPrivate(key);
}
/// <summary>
/// 判断缓存中是否含有缓存该键
/// </summary>
public static bool Exists(string key)
{
return (GetPrivate(key) != null);
}
/// <summary>
/// 移除缓存对象
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool Remove(string key)
{
if (string.IsNullOrEmpty(key))
{
return false;
}
HttpRuntime.Cache.Remove(key);
return true;
}
/// <summary>
/// 移除所有缓存
/// </summary>
/// <returns></returns>
public static bool RemoveAll()
{
IDictionaryEnumerator iDictionaryEnumerator = HttpRuntime.Cache.GetEnumerator();
while (iDictionaryEnumerator.MoveNext())
{
HttpRuntime.Cache.Remove(Convert.ToString(iDictionaryEnumerator.Key));
}
return true;
}
/// <summary>
/// 尝试获取缓存,不存在则执行匿名委托
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="func"></param>
/// <param name="Seconds">设置缓存时间;单位:秒</param>
/// <returns></returns>
public static T TryGet<T>(string key, Func<T> func, double Seconds)
{
if (Exists(key)) return (T)Get(key);
var result = func.Invoke();
Set(key, result, Seconds);
return result;
}
/// <summary>
/// 设置缓存
/// </summary>
public static bool Set(string key, object value, CacheDependency cacheDependency, DateTime dateTime,
TimeSpan timeSpan, CacheItemPriority cacheItemPriority, CacheItemRemovedCallback cacheItemRemovedCallback)
{
if (string.IsNullOrEmpty(key) || value == null)
{
return false;
}
HttpRuntime.Cache.Insert(key, value, cacheDependency, dateTime, timeSpan, cacheItemPriority,
cacheItemRemovedCallback);
return true;
}
/// <summary>
/// 获取缓存
/// </summary>
private static object GetPrivate(string key)
{
return string.IsNullOrEmpty(key) ? null : HttpRuntime.Cache.Get(key);
}
}
public class UserInfoModel
{
public int ID { get; set; }
public string Type { get; set; }
public string name { get; set; }
}
//使用方法:
#region 设置缓存,将 token放置在缓存中,1.5个小时过期,防止频繁请求token
string SetCacheStatusMsg = "初始数据";
string CacheKeyUserList = "CacheKeyUserList";
List<UserInfoModel> ListCacheData = null;
if (!CacheHelp.Exists(CacheKeyUserList))
{
CacheHelp.RemoveAll();//移除所有缓存,放置缓存太多影响内存
#region 增加缓存
//造数据(可以直接数据库访问获得数据)
List<UserInfoModel> list = new List<UserInfoModel>();
// for (int i = 1; i < 6; i++)
// {
DingDingHelper DDing = new DingDingHelper();
AccessTokenResult DDtoken = DDing.GetAccessToken0();
DDToken = DDtoken.access_token;
// QYWeiChartHelper QYWX = new QYWeiChartHelper();//QYWXchatid
// QYTokenResult QYToken = QYWX.QYWXGetToken();
// QYwxToken = QYToken.access_token;
UserInfoModel userinfo = new UserInfoModel();
userinfo.Type = "钉钉";
userinfo.name = DDToken;
list.Add(userinfo);
UserInfoModel userinfo2 = new UserInfoModel();
userinfo2.Type = "企业微信";
userinfo2.name = QYwxToken;
list.Add(userinfo2);
// }
ListCacheData = list;
bool SetCacheStatus = CacheHelp.Set(
key: CacheKeyUserList,
value: list,
Seconds: 5400 //缓存时长,单位“秒”
);
if (SetCacheStatus)
{
SetCacheStatusMsg = "增加缓存成功";
}
else
{
SetCacheStatusMsg = "增加缓存失败";
}
#endregion
}
else
{
#region 获取缓存
ListCacheData = (List<UserInfoModel>)CacheHelp.Get(CacheKeyUserList);
DDToken = ListCacheData[0].name;
QYwxToken = ListCacheData[1].name;
#endregion
}
#endregion