最近在微信第三方平台項目開發中,有一個需求,所有綁定的公眾號的回復規則按照主公眾號的關鍵詞配置來處理,我的處理思路是獲取主公眾號配置的關鍵詞回復規則,緩存10分鍾,由於需要使用Redis緩存來存儲一些數據,看來一下底層的實現,是使用HashSet的結構數據,而HashSet是不會過期的,通過在群里的交流,有一位管理員介紹說可以給值設置緩存過期時間,我按照思路實現了一下:
/// <summary> /// HashSetCacheModel<T> /// HashSet結構 /// /// 修改紀錄 /// /// 2018-07-02版本:1.0 JiShiYu 創建文件。 /// /// <author> /// <name>JiShiYu</name> /// <date>2018-07-02</date> /// </author> /// </summary> public class HashSetCacheModel<T> { /// <summary> /// 進入緩存的時間 /// </summary> public DateTime CreateOn { set; get; } = DateTime.Now; /// <summary> /// 緩存過期時間 /// </summary> public DateTime ExpireAt { set; get; } /// <summary> /// 緩存對象的值 /// </summary> public T Value { get; set; } } }
該類實現的是將存儲的值進行再一次包裝,增加創建和過期的時間。
在方法中使用,每次取值時判斷一下是否過期,如果過期就重新獲取一次,並更新緩存
/// <summary> /// 獲取主公眾號自動回復規則設置 /// </summary> /// <returns></returns> protected GetCurrentAutoreplyInfoResult GetCurrentAutoreplyInfo() { // 進行緩存 GetCurrentAutoreplyInfoResult infoResult = null; try { IContainerCacheStrategy containerCache = LocalContainerCacheStrategy.Instance; IBaseObjectCacheStrategy baseCache = containerCache.BaseCacheStrategy(); string key = "AutoreplyInfo:" + appId; HashSetCacheModel<GetCurrentAutoreplyInfoResult> cacheModel = null; if (baseCache.CheckExisted(key)) { cacheModel = baseCache.Get<HashSetCacheModel<GetCurrentAutoreplyInfoResult>>(key); if (cacheModel.ExpireAt < DateTime.Now) { // 過期了,要更新一次 infoResult = AutoReplyApi.GetCurrentAutoreplyInfo(appId); cacheModel = new HashSetCacheModel<GetCurrentAutoreplyInfoResult>(); cacheModel.CreateOn = DateTime.Now; cacheModel.ExpireAt = DateTime.Now.AddMinutes(10); cacheModel.Value = infoResult; baseCache.Update(key, cacheModel); } infoResult = cacheModel.Value; } else { infoResult = AutoReplyApi.GetCurrentAutoreplyInfo(appId); cacheModel = new HashSetCacheModel<GetCurrentAutoreplyInfoResult>(); cacheModel.CreateOn = DateTime.Now; cacheModel.ExpireAt = DateTime.Now.AddMinutes(10); cacheModel.Value = infoResult; baseCache.Set(key, cacheModel); } } catch (Exception ex) { NLogHelper.Warn(ex, "GetCurrentAutoreplyInfo"); } return infoResult; }
大家看看怎樣呢?