CacheHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
namespace ZZAYwebservice.wechat
{
public class CacheHelper
{
/// <summary>
/// 讀取緩存數據
/// </summary>
/// <param name="cacheKey">鍵</param>
/// <returns></returns>
public static object GetCache(string cacheKey)
{
var objCache = HttpRuntime.Cache.Get(cacheKey);
return objCache;
}
/// <summary>
/// 設置緩存數據
/// </summary>
/// <param name="cacheKey">鍵</param>
/// <param name="content">值</param>
public static void SetCache(string cacheKey, object content)
{
var objCache = HttpRuntime.Cache;
objCache.Insert(cacheKey, content);
}
/// <summary>
/// 設置緩存數據並且設置默認過期時間
/// </summary>
/// <param name="cacheKey"></param>
/// <param name="content"></param>
/// <param name="timeOut"></param>
public static void SetCache(string cacheKey, object content, int timeOut = 3600)
{
try
{
if (content == null)
{
return;
}
var objCache = HttpRuntime.Cache;
//設置絕對過期時間
//絕對時間過期。DateTime.Now.AddSeconds(10)表示緩存在3600秒後過期,TimeSpan.Zero表示不使用平滑過期策略。
objCache.Insert(cacheKey, content, null, DateTime.Now.AddSeconds(timeOut), TimeSpan.Zero, CacheItemPriority.High, null);
//相對過期
//DateTime.MaxValue表示不使用絕對時間過期策略,TimeSpan.FromSeconds(10)表示緩存連續10秒沒有訪問就過期。
//objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null);
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 移除指定緩存
/// </summary>
/// <param name="cacheKey">鍵</param>
public static void RemoveAllCache(string cacheKey)
{
var objCache = HttpRuntime.Cache;
objCache.Remove(cacheKey);
}
/// <summary>
/// 刪除全部緩存
/// </summary>
public static void RemoveAllCache()
{
var objCache = HttpRuntime.Cache;
var cacheEnum = objCache.GetEnumerator();
while (cacheEnum.MoveNext())
{
objCache.Remove(cacheEnum.Key.ToString());
}
}
}
}
調用方法:
/// <summary>
/// 初始化,序列化
/// </summary>
public void Initialize()
{
object msg = CacheHelper.GetCache("NApptoken");
if (msg == null)
{
var tokenResult = iSVOpenInterfaceProxy.GetAppToken(new com.tencent.healthcard.HealthOpenAuth.CommonIn
{
requestId = System.Guid.NewGuid().ToString(),
hospitalId = LxAppConfig.GetHospitalId()
}, new GetAppTokenReq
{
appId = LxAppConfig.GetAppid()
});
var commonOut = (com.tencent.healthcard.HealthOpenAuth.CommonOut)
(tokenResult["commonOut"]);
var rsp = (GetAppTokenRsp)tokenResult["rsp"];
appToken = rsp.appToken;
CacheHelper.SetCache("NApptoken", rsp.appToken, 7200);
}
else
{
appToken = msg.ToString();
}
}