yz_server/Server/Utils/CacheHelper.cs

121 lines
2.8 KiB
C#
Raw Permalink Normal View History

2022-04-16 07:48:12 +00:00
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
namespace Server.Utils
{
/// <summary>
/// 缓存操作,默认缓存1分钟
/// </summary>
public class CacheHelper
{
#region
private static CacheHelper ini;
public static CacheHelper GetIntance()
{
if (ini == null)
{
ini = new CacheHelper();
}
return ini;
}
private CacheHelper() { }
#endregion
/// <summary>
/// 缓存容器
/// </summary>
static System.Web.Caching.Cache objCache = new System.Web.Caching.Cache();
/// <summary>
/// 设置数据缓存
/// </summary>
public void SetCache(string CacheKey, object objObject, int timeout = 7200)
{
if (objCache.Get(CacheKey) != null)
{
objCache.Remove(CacheKey);
}
objCache.Insert(CacheKey, objObject, null, DateTime.Now.AddSeconds(timeout), TimeSpan.Zero);
}
/// <summary>
/// 获取当前应用程序指定CacheKey的Cache值
/// </summary>
/// <param name="CacheKey">
/// <returns></returns>y
public object GetCache(string CacheKey)
{
return objCache[CacheKey];
}
/// <summary>
/// 清除单一键缓存
/// </summary>
/// <param name="key">
public void RemoveKeyCache(string CacheKey)
{
try
{
objCache.Remove(CacheKey);
}
catch { }
}
/// <summary>
/// 清除所有缓存
/// </summary>
public void RemoveAllCache()
{
IDictionaryEnumerator CacheEnum = objCache.GetEnumerator();
if (objCache.Count > 0)
{
ArrayList al = new ArrayList();
while (CacheEnum.MoveNext())
{
al.Add(CacheEnum.Key);
}
foreach (string key in al)
{
objCache.Remove(key);
}
}
}
/// <summary>
/// 以列表形式返回已存在的所有缓存
/// </summary>
/// <returns></returns>
public ArrayList ShowAllCache()
{
ArrayList al = new ArrayList();
if (objCache.Count > 0)
{
IDictionaryEnumerator CacheEnum = objCache.GetEnumerator();
while (CacheEnum.MoveNext())
{
al.Add(CacheEnum.Key);
}
}
return al;
}
}
}