Cache的封装和使用
ICache 接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Hzb.Utils.Caching
{
/// <summary>
/// Cache manager interface
/// </summary>
public interface ICache
{
/// <summary>
/// Gets or sets the value associated with the specified key.
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="key">The key of the value to get.</param>
/// <returns>The value associated with the specified key.</returns>
T Get<T>(string key); /// <summary>
/// Adds the specified key and object to the cache.
/// </summary>
/// <param name="key">key</param>
/// <param name="data">Data</param>
/// <param name="cacheTime">Cache time</param>
void Add(string key, object data, int cacheTime = ); /// <summary>
/// Gets a value indicating whether the value associated with the specified key is cached
/// </summary>
/// <param name="key">key</param>
/// <returns>Result</returns>
bool Contains(string key); /// <summary>
/// Removes the value with the specified key from the cache
/// </summary>
/// <param name="key">/key</param>
void Remove(string key); /// <summary>
/// Clear all cache data
/// </summary>
void RemoveAll(); object this[string key] { get; set; } int Count { get; }
}
}
CacheManager 管理类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Hzb.Utils.Caching
{
public class CacheManager
{
private CacheManager()
{ } private static ICache cache = null; static CacheManager()
{
//// //可以创建不同的cache对象
cache = (ICache)Activator.CreateInstance(typeof(MemoryCache));// 这里可以根据配置文件来选择
//cache = (ICache)Activator.CreateInstance(typeof(CustomerCache));
} #region ICache /// <summary>
/// 获取缓存,假如缓存中没有,可以执行委托,委托结果,添加到缓存
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="key">键</param>
/// <param name="acquire">委托 为null会异常</param>
/// <param name="cacheTime">缓存时间</param>
/// <returns></returns>
public static T Get<T>(string key, Func<T> acquire, int cacheTime = )
{
if (cache.Contains(key))
{
return GetData<T>(key);
}
else
{
T result = acquire.Invoke();//执行委托 获取委托结果 作为缓存值
cache.Add(key, result, cacheTime);
return result;
}
} /// <summary>
/// 当前缓存数据项的个数
/// </summary>
public static int Count
{
get { return cache.Count; }
} /// <summary>
/// 如果缓存中已存在数据项键值,则返回true
/// </summary>
/// <param name="key">数据项键值</param>
/// <returns>数据项是否存在</returns>
public static bool Contains(string key)
{
return cache.Contains(key);
} /// <summary>
/// 获取缓存数据
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static T GetData<T>(string key)
{
return cache.Get<T>(key);
} /// <summary>
/// 添加缓存数据。
/// 如果另一个相同键值的数据已经存在,原数据项将被删除,新数据项被添加。
/// </summary>
/// <param name="key">缓存数据的键值</param>
/// <param name="value">缓存的数据,可以为null值</param>
public static void Add(string key, object value)
{
if (Contains(key))
cache.Remove(key);
cache.Add(key, value);
} /// <summary>
/// 添加缓存数据。
/// 如果另一个相同键值的数据已经存在,原数据项将被删除,新数据项被添加。
/// </summary>
/// <param name="key">缓存数据的键值</param>
/// <param name="value">缓存的数据,可以为null值</param>
/// <param name="expiratTime">缓存过期时间间隔(单位:秒) 默认时间600秒</param>
public static void Add(string key, object value, int expiratTime = )
{
cache.Add(key, value, expiratTime);
} /// <summary>
/// 删除缓存数据项
/// </summary>
/// <param name="key"></param>
public static void Remove(string key)
{
cache.Remove(key);
} /// <summary>
/// 删除所有缓存数据项
/// </summary>
public static void RemoveAll()
{
cache.RemoveAll();
}
#endregion }
}
asp.net 系统缓存封装
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Runtime.Caching;
using System.Text.RegularExpressions; namespace Hzb.Utils.Caching
{
/// <summary>
/// Represents a MemoryCacheCache
/// </summary>
public partial class MemoryCache : ICache
{
public MemoryCache() { } protected ObjectCache Cache
{
get
{
return System.Runtime.Caching.MemoryCache.Default;
}
} /// <summary>
/// Gets or sets the value associated with the specified key.
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="key">The key of the value to get.</param>
/// <returns>The value associated with the specified key.</returns>
public T Get<T>(string key)
{
if (Cache.Contains(key))
{
return (T)Cache[key];
} else
{
return default(T);
}
} public object Get(string key)
{
//int iResult= Get<Int16>("123"); return Cache[key];
} /// <summary>
/// Adds the specified key and object to the cache.
/// </summary>
/// <param name="key">key</param>
/// <param name="data">Data</param>
/// <param name="cacheTime">Cache time(unit:minute) 默认30秒</param>
public void Add(string key, object data, int cacheTime = )
{
if (data == null)
return; var policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromSeconds(cacheTime);
Cache.Add(new CacheItem(key, data), policy);
} /// <summary>
/// Gets a value indicating whether the value associated with the specified key is cached
/// </summary>
/// <param name="key">key</param>
/// <returns>Result</returns>
public bool Contains(string key)
{
return Cache.Contains(key);
} public int Count { get { return (int)(Cache.GetCount()); } } /// <summary>
/// Removes the value with the specified key from the cache
/// </summary>
/// <param name="key">/key</param>
public void Remove(string key)
{
Cache.Remove(key);
} /// <summary>
/// Removes items by pattern
/// </summary>
/// <param name="pattern">pattern</param>
public void RemoveByPattern(string pattern)
{
var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
var keysToRemove = new List<String>(); foreach (var item in Cache)
if (regex.IsMatch(item.Key))
keysToRemove.Add(item.Key); foreach (string key in keysToRemove)
{
Remove(key);
}
} /// <summary>
/// 根据键值返回缓存数据
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public object this[string key]
{
get { return Cache.Get(key); }
set { Add(key, value); }
} /// <summary>
/// Clear all cache data
/// </summary>
public void RemoveAll()
{
foreach (var item in Cache)
Remove(item.Key);
}
}
}
自定义缓存
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Hzb.Utils.Caching
{
/// <summary>
/// 自定义缓存类
/// </summary>
public class CustomerCache : ICache
{
private static Dictionary<string, KeyValuePair<object, DateTime>> DATA = new Dictionary<string, KeyValuePair<object, DateTime>>(); /// <summary>
/// 获取缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T Get<T>(string key)
{
if (!this.Contains(key))
{
return default(T); //defalut t 是返回默认的T,比如引用就是返回null int返回0
}
else
{
KeyValuePair<object, DateTime> keyValuePair = DATA[key];
if (keyValuePair.Value < DateTime.Now)//过期
{
this.Remove(key);
return default(T);
}
else
{
return (T)keyValuePair.Key;
}
}
} /// <summary>
/// 添加缓存
/// </summary>
/// <param name="key"></param>
/// <param name="data"></param>
/// <param name="cacheTime">过期时间 默认30秒 </param>
public void Add(string key, object data, int cacheTime = )
{
DATA.Add(key, new KeyValuePair<object, DateTime>(data, DateTime.Now.AddSeconds(cacheTime))); // DATA.Add(key, new KeyValuePair<object, DateTime>(data, DateTime.Now.AddMinutes(cacheTime)));
} /// <summary>
/// 判断包含
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool Contains(string key)
{
return DATA.ContainsKey(key);
} /// <summary>
/// 移除
/// </summary>
/// <param name="key"></param>
public void Remove(string key)
{
DATA.Remove(key);
} /// <summary>
/// 全部删除
/// </summary>
public void RemoveAll()
{
DATA = new Dictionary<string, KeyValuePair<object, DateTime>>();
} /// <summary>
/// 获取
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public object this[string key]
{
get
{
return this.Get<object>(key);
}
set
{
this.Add(key, value);
}
} /// <summary>
/// 数量
/// </summary>
public int Count
{
get
{
return DATA.Count(d => d.Value.Value > DateTime.Now);
}
}
}
}
调用代码 :拿用户登录做列子
using Hzb.Model;
using Hzb.Model.SysEnum;
using Hzb.PC.Bll.Interface;
using Hzb.Utils.Caching;
using Hzb.Utils.Cookie;
using Hzb.Utils.Regular;
using Hzb.Utils.Secret;
using Hzb.Utils.Session;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace Hzb.Web.Controllers
{
public class AccountController : Controller
{
private IBaseBLL<User> IUserBLL = null; /// <summary>
/// 构造函数注入
/// </summary>
[InjectionConstructor]
public AccountController(IBaseBLL<User> userBLL)
{
IUserBLL = userBLL;
} /// <summary>
/// 【视图】 登陆
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult Login(string msg)
{
ViewData.Model = msg;
return View();
} /// <summary>
/// 【处理程序】 登陆
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult PoccLogin(string username, string password)
{
bool b = Validator.IsPhoneNumber(username); User model = null;
if (b)
{
model = IUserBLL.DBSet().Where(m => m.Account == username).FirstOrDefault();
}
else
{
int _id;
if (int.TryParse(username, out _id))
{
model = IUserBLL.DBSet().Where(m => m.Id == _id).FirstOrDefault();
}
} if (model != null)
{
password = "hzb_" + password + "_zhonghu"; if ((UserEnum)model.State == UserEnum.Normal)
{
if (model.Password == MD5Helper.MD5FromString(password))
{
//添加cookie值
CookieHelper.AddSingleValueCookie("key", model.Id.ToString(), DateTime.Now.AddHours());
//添加缓存
CacheManager.Add(model.Id.ToString(), model, );
//获取session
string returntUrl = SessionHelper.GetSessionString("ReturntUrl");
if (!string.IsNullOrEmpty(returntUrl))
{
return Redirect(returntUrl);
}
else
{
UserTypeEnum type = (UserTypeEnum)model.Type;
switch (type)
{
case UserTypeEnum.Owner:
return RedirectToAction("Index", "Home", new { area = "User", id = model.Id });
case UserTypeEnum.Company:
return RedirectToAction("Index", "Home", new { area = "Company", id = model.Id });
case UserTypeEnum.Designer:
return RedirectToAction("Index", "Home", new { area = "Designer", id = model.Id });
case UserTypeEnum.Manager:
return RedirectToAction("Index", "Home", new { area = "Manager", id = model.Id });
case UserTypeEnum.Supplier:
return RedirectToAction("Index", "Home", new { area = "Supplier", id = model.Id });
default:
return RedirectToAction("CustomerError", "Shared", new { msg = "程序错误" });
}
}
}
else
{
return RedirectToAction("Login", new { msg = "密码错误" }); }
}
else
{
return RedirectToAction("Login", new { msg = "账号已删除" });
} }
else
{
return RedirectToAction("Login", new { msg = "账号不存在" });
} } /// <summary>
/// 【处理程序】 退出
/// </summary>
[HttpGet]
public ActionResult Logout()
{
//获取cookie值
string cookie_value = CookieHelper.GetSingleValueCookieValue("key"); //清除缓存
CacheManager.Remove(cookie_value); //清除cookie值
CookieHelper.DelSingleValueCookie(cookie_value); return RedirectToAction("Login", "Account");
}
}
}
MVC检验登陆和权限的filter
using Hzb.Model;
using Hzb.Utils.Caching;
using Hzb.Utils.Cookie;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace Hzb.Web.Utility.Filter
{
/// <summary>
/// 检验登陆和权限的filter
/// </summary>
[AttributeUsage(AttributeTargets.All, Inherited = true)]
public class AuthorityFilter : AuthorizeAttribute
{
/// <summary>
/// 检查用户登录
/// </summary>
/// <param name="filterContext"></param>
public override void OnAuthorization(AuthorizationContext filterContext)
{
//获取cookie值
string cookie_value = CookieHelper.GetSingleValueCookieValue("key");
//获取缓存
var cacheUser = CacheManager.GetData<User>(cookie_value); if (cacheUser == null)
{
HttpContext.Current.Session["ReturntUrl"] = filterContext.RequestContext.HttpContext.Request.RawUrl;
filterContext.Result = new RedirectResult("/Account/Login");
return;
}
else
{
//清除缓存
CacheManager.Remove(cookie_value);
//重新添加缓存
CacheManager.Add(cookie_value, cacheUser, );
return;
}
}
}
}
特性AuthorityFilter验证是否登陆
using Hzb.Model;
using Hzb.Model.SysEnum;
using Hzb.Model.ViewModel;
using Hzb.PC.Bll.Interface;
using Hzb.Utils.Caching;
using Hzb.Utils.Cookie;
using Hzb.Utils.Session;
using Hzb.Web.Utility.Filter;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HzbModel = Hzb.Model; namespace Hzb.Web.Areas.Company.Controllers
{ public class HomeController : Controller
{
private IUserManagerBll IUserManagerBll = null; /// <summary>
/// 构造函数注入
/// </summary>
[InjectionConstructor]
public HomeController(IUserManagerBll userManagerBll)
{
IUserManagerBll = userManagerBll;
} /// <summary>
/// 【视图】 首页
/// </summary>
/// <returns></returns>
[AuthorityFilter]
public ActionResult Index(int id = )
{
//获取cookie
string cookie_value = CookieHelper.GetSingleValueCookieValue("key");
//获取缓存
var obj = CacheManager.GetData<HzbModel.User>(cookie_value);
if (obj != null)
{
if (obj.Id == id)
{
ViewUser model = IUserManagerBll.GetViewUser(id);
ViewData.Model = model;
return View();
}
else
{
return Redirect("/Account/Login");
}
}
else
{
return Redirect("/Account/Login");
}
} /// <summary>
/// 部分视图【左侧菜单】
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ActionResult Menu(int id)
{
ViewData.Model = id;
return View();
}
}
}
转自:https://blog.csdn.net/u014742815/article/details/53095925
Cache的封装和使用的更多相关文章
- Something about cache
http://www.tyut.edu.cn/kecheng1/2008/site04/courseware/chapter5/5.5.htm 5.5 高速缓冲存储器cache 随着CPU时钟速率的不 ...
- 基于PHP的一种Cache回调与自动触发技术
$s = microtime(true); for($i=0; $iaaa($array, $array, $array); $data = a::bbb($array, $array, $array ...
- 异步 HttpContext.Current 为空null 另一种解决方法
1.场景 在导入通讯录过程中,把导入的失败.成功的号码数进行统计,然后保存到session中,客户端通过轮询显示状态. 在实现过程中,使用的async调用方法,出现HttpContext.Curren ...
- Android网络框架源码分析一---Volley
转载自 http://www.jianshu.com/p/9e17727f31a1?utm_campaign=maleskine&utm_content=note&utm_medium ...
- 【javascript基础】8、闭包
前言 函数和作用域啥的我们前面已经了解了,现在就要学习闭包了,这是一个挺晦涩的知识点,初学者可能会感觉不好理解,但是高手都不不以为然了,高手就给我提点意见吧,我和新手一起来学习什么是闭包. 例子 先不 ...
- Ehcache(09)——缓存Web页面
http://haohaoxuexi.iteye.com/blog/2121782 页面缓存 目录 1 SimplePageCachingFilter 1.1 calculate ...
- fork安全的gettid高效实现
进程有id,可以通过getpid()获得,线程也有id,但是glibc没有提供封装.需要自己发出系统调用.在关键路径,系统调用还是对性能有影响的.因此我们可以想到类似glibc对getpid做的cac ...
- Android开源框架源码分析:Okhttp
一 请求与响应流程 1.1 请求的封装 1.2 请求的发送 1.3 请求的调度 二 拦截器 2.1 RetryAndFollowUpInterceptor 2.2 BridgeInterceptor ...
- Vue音乐项目笔记(五)
1.搜索列表的点击删除.删除全部的交互事件 https://blog.csdn.net/weixin_40814356/article/details/80496097 seach组件中放search ...
随机推荐
- Webpack Tapable原理详解
directory - src - sim ---- 简单的模拟实现 - /.js$/ ---- 使用 代码已上传github, 地址 Detailed Webpack 就像一条生产线, 要经过一系列 ...
- 技能get:用HTML5实现波浪效果
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...
- 数论(一)LOJ1282
1.题目来源LOJ1282 You are given two integers: n and k, your task is to find the most significant three d ...
- 实践笔记-VA05 销售订单清单 增加字段
现在都自开发很多报表 ,估计没有多少人 用 VA05 1.在结构 VBMTVZ 中增加需要的字段 2.表t180a 中 添加一条 “添加字段”的数据,如下: 3.取值 修改程序 INCLUDE V ...
- ABAP术语-Data Browser
Data Browser 原文:http://www.cnblogs.com/qiangsheng/archive/2008/01/21/1046858.html Tool for displayin ...
- 构建高可靠hadoop集群之0-hadoop用户向导
本文翻译自:http://hadoop.apache.org/docs/r2.8.0/hadoop-project-dist/hadoop-hdfs/HdfsUserGuide.html 基于2.8. ...
- 使用Python第三方库生成二维码
本文主要介绍两个可用于生成二维码的Python第三方库:MyQR和qrcode. MyQR的使用: 安装: pip install MyQR 导入: from MyQR import myqr imp ...
- p标签内不能含有块元素。
原来一直听网上这样说.自己并没有实际遇到过.上例子. <!DOCTYPE html> <html> <head> <meta charset="ut ...
- ECSHOP快递单号查询插件圆通V8.2专版
本ECSHOP快递物流单号跟踪插件提供国内外近2000家快递物流订单单号查询服务例如申通快递.顺丰快递.圆通快递.EMS快递.汇通快递.宅急送快递.德邦物流.百世快递.汇通快递.中通快递.天天快递等知 ...
- fabric Report API
1.Token生成 接口 : post https://fabric.io/oauth/token 请求头:Headers Content-Type : application/json 正文: bo ...