类:
cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;
namespace RisunFactoryLibrary
{
public class CacheHelper
{
/// <summary>
/// 创建缓存项的文件依赖
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="obj">object对象</param>
/// <param name="fileName">文件绝对路径</param>
public static void Insert(string key, object obj, string fileName)
{
//创建缓存依赖项
CacheDependency dep = new CacheDependency(fileName);
//创建缓存
HttpContext.Current.Cache.Insert(key, obj, dep);
}
/// <summary>
/// 创建缓存项的文件依赖
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="obj">object对象</param>
/// <param name="fileName">文件绝对路径</param>
public static void Remove(string key)
{
//创建缓存
HttpContext.Current.Cache.Remove(key);
}
/// <summary>
/// 创建缓存项过期
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="obj">object对象</param>
/// <param name="expires">过期时间(分钟)</param>
public static void Insert(string key, object obj, int expires)
{
HttpContext.Current.Cache.Insert(key, obj, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, expires, 0));
}
/// <summary>
/// 获取缓存对象
/// </summary>
/// <param name="key">缓存Key</param>
/// <returns>object对象</returns>
public static object Get(string key)
{
if (string.IsNullOrEmpty(key))
{
return null;
}
return HttpContext.Current.Cache.Get(key);
}
/// <summary>
/// 获取缓存对象
/// </summary>
/// <typeparam name="T">T对象</typeparam>
/// <param name="key">缓存Key</param>
/// <returns></returns>
public static T Get<T>(string key)
{
object obj = Get(key);
return obj == null ? default(T) : (T)obj;
}
}
}
调用:
cs
List<object> records = new List<object>();
records.Add(new {
id:1,
data:"2024-01-01 00:00:00"
});
records.Add(new {
id:2,
data:"2024-01-02 00:00:00"
});
records.Add(new {
id:3,
data:"2024-01-03 00:00:00"
});
CacheHelper.Insert("attendanceRecords_json", records, 600);//插入缓存记录,设置过期时间为十分钟
CacheHelper.Remove("record");//删除记录缓存
一般用于数据去重,例如在插入考勤记录时,过滤1分钟内重复出现的人员记录,可获取1分钟内出现的人员记录,在每次插入时判断当前人员是否1分钟内出现,如果出现则不插入记录。需要保证缓存记录一直为最新的记录。
可能存在的BUG,当同一人员的两次请求的时间间隔过短时(并发),可能在两次请求处理时缓存数据中均不存在该人员信息,会导致同时插入两条该人员信息(无法去重情况),暂时未遇到该种情况,遇到后更新解决办法