您的位置:首页 > 其它

缓存

2015-08-24 16:50 281 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.Web.Caching;

namespace WebApiDemo.Common
{
public class CacheHelper
{
public static object Get(string cacheKey)
{
return HttpRuntime.Cache[cacheKey];
}
public static void Add(string cacheKey, object obj, int cacheMinute)
{
HttpRuntime.Cache.Insert(cacheKey, obj, null, DateTime.Now.AddMinutes(cacheMinute),
Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
}
}

public class MyCache
{
public object GetMemberSigninDays5()
{
const int cacheTime = 5;
const string cacheKey = "mushroomsir";

//缓存标记。
const string cacheSign = cacheKey + "_Sign";
var sign = CacheHelper.Get(cacheSign);

//获取缓存值
var cacheValue = CacheHelper.Get(cacheKey);
if (sign != null)
return cacheValue; //未过期,直接返回。

lock (cacheSign)
{
sign = CacheHelper.Get(cacheSign);
if (sign != null)
return cacheValue;

CacheHelper.Add(cacheSign, "1", cacheTime);
ThreadPool.QueueUserWorkItem((arg) =>
{
cacheValue = "395"; //这里一般是 sql查询数据。 例:395 签到天数
CacheHelper.Add(cacheKey, cacheValue, cacheTime * 2); //日期设缓存时间的2倍,用于脏读。
});
}
return cacheValue;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: