缓存-避免频繁操作

int flag = 0;
int seconds=8;
if (Library.DataCache.GetCache(“Lock-” + UserID) != null)//判断是否锁定
{
flag = (int)Library.DataCache.GetCache(“Lock-” +UserID);
if (flag == 1)//如果锁定 返回
{
return Result(1, “请不要频繁操作!”);
}
}
Library.DataCache.SetCache(“Lock-” +UserID, 1, seconds);
处理代码
Library.DataCache.Remove(“Lock-” +UserID);//解锁

这里是引用
using System;
using System.Collections;
using System.Web;
using System.Web.Caching;
namespace Library
{
///
/// 缓存相关的操作类
///
public class DataCache
{
///
/// 清理缓存
///
public static void Clear()
{
IDictionaryEnumerator enumerator = HttpContext.Current.Cache.GetEnumerator();
while (enumerator.MoveNext())
{
HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
}
}
///
/// 判断某缓存值是否存在
///
///
///
public static bool Contains(string key)
{
return (HttpContext.Current.Cache[key] != null);
}
///
/// 获取缓存值
///
///
///
public static object GetCache(string key)
{
try
{
if (HttpContext.Current.Cache[key] != null)
{
return HttpContext.Current.Cache[key];
}
}
catch
{
}
return null;
}
///
/// 获取缓存值且转换为字符串类型
///
///
///
public static string GetCacheToString(string key)
{
try
{
if (HttpContext.Current.Cache[key] != null)
{
return ToString(HttpContext.Current.Cache[key]);
}
}
catch
{
}
return “”;
}
///
/// 移除某缓存值
///
///
public static void Remove(string key)
{
try
{
if (HttpContext.Current.Cache[key] != null)
{
HttpContext.Current.Cache.Remove(key);
}
}
catch
{
}
}
///
/// 模糊移除某些缓存值
///
/// 如: housing_follow_json_11200
public static void RemoveLike(string likekey)
{
System.Web.Caching.Cache _cache = HttpRuntime.Cache;
IDictionaryEnumerator CacheEnum = _cache.GetEnumerator(); // 所有缓存枚举
string key = “”;
while (CacheEnum.MoveNext())
{
key = CacheEnum.Key.ToString();
if (key.Contains(likekey))
Remove(key);
}
}
///
/// 设置缓存值
///
/// 键值
/// 缓存内容
/// 缓存秒数
///
public static bool SetCache(string key, object value, int seconds)
{
if (value == null)
{
return SetCache(key, “”, seconds);
}
try
{
if (HttpContext.Current.Cache[key] != null)
{
HttpContext.Current.Cache.Remove(key);
}
if (seconds <= 0)
{
HttpContext.Current.Cache.Insert(key, value, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(1.0), CacheItemPriority.NotRemovable, null);
}
else
{
HttpContext.Current.Cache.Insert(key, value, null, DateTime.Now.AddSeconds((double)seconds), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
}
return true;
}
catch
{
}
return false;
}
private static string ToString(object obj)
{
if (obj == null)
{
return “”;
}
return obj.ToString();
}
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值