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();
}
}
}