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 ...
随机推荐
- 【前行】◇第3站◇ 国庆训练营·OI制模拟赛
[第3站] 国庆训练营·OI制模拟赛Ⅰ 怀着冲刺提高组400的愿望来到这个very small but very interesting 的训练营QwQ 在北大dalao的带领下开始了第一场OI模拟赛 ...
- 针对 npm ERR! cb() never called! 问题
在开发项目安装依赖时(npm install) 往往会报 npm ERR! cb()never called!的错误 如图: 解决方法: 一.首先要以管理员模式打开cmd清除你的npm缓存 : np ...
- npm run build打包后自定义动画没有执行
问题描述:在vue项目中,当你自己写了一些自定义动画效果,然后你npm run build打包项目放到线上环境后,发现动画并没有效果. 解决办法:在vue项目中找到build文件夹下的vue-load ...
- scala成长之路(2)对象和类
scala提供了一种特殊的定义单例的方法:object关键字 scala> object Shabi{ | val age = 0 | val name = "shabi" ...
- DHT11资料
产品名:温湿度传感器 型号:DHT11 厂商:奥松电子 参数: 相对湿度: 分辨率:0.1%RH 16Bit 精度:25℃ 正负 %2 温度: 分辨率:0.1%RH 16 ...
- ubuntu64位运行32位程序
sudo dpkg --add-architecture i386 sudo apt install libc6:i386 转:https://blog.csdn.net/zoomdy/article ...
- MongoDB入门---简介
最近呢,刚好有一些时间,所以就学习了一下新的数据库类型MongoDB.要想了解这个MongoDB,我们首先需要了解一个概念,那就是nosql(not only sql).一下就是官方的概念: NoSQ ...
- CentOS7 添加自定义系统服务案例
示例一: 执行脚本/root/project/systemctl/test.sh() ######################################################### ...
- shell eval命令使用
eval命令将会首先扫描命令行进行所有的置换,然后再执行该命令. 该命令适用于那些一次扫描无法实现其功能的变量.该命令对变量进行两次扫描. 这些需要进行两次扫描的变量有时被称为复杂变量.不过这些变量本 ...
- python中判断输入是否为数字(包括浮点数)
1.当num确定为数字后 num=123.4print(isinstance(num,float))#判断是否为浮点数 print(isinstance(num,int))#判断是否为整数 2.当nu ...