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的封装和使用的更多相关文章

  1. Something about cache

    http://www.tyut.edu.cn/kecheng1/2008/site04/courseware/chapter5/5.5.htm 5.5 高速缓冲存储器cache 随着CPU时钟速率的不 ...

  2. 基于PHP的一种Cache回调与自动触发技术

    $s = microtime(true); for($i=0; $iaaa($array, $array, $array); $data = a::bbb($array, $array, $array ...

  3. 异步 HttpContext.Current 为空null 另一种解决方法

    1.场景 在导入通讯录过程中,把导入的失败.成功的号码数进行统计,然后保存到session中,客户端通过轮询显示状态. 在实现过程中,使用的async调用方法,出现HttpContext.Curren ...

  4. Android网络框架源码分析一---Volley

    转载自 http://www.jianshu.com/p/9e17727f31a1?utm_campaign=maleskine&utm_content=note&utm_medium ...

  5. 【javascript基础】8、闭包

    前言 函数和作用域啥的我们前面已经了解了,现在就要学习闭包了,这是一个挺晦涩的知识点,初学者可能会感觉不好理解,但是高手都不不以为然了,高手就给我提点意见吧,我和新手一起来学习什么是闭包. 例子 先不 ...

  6. Ehcache(09)——缓存Web页面

    http://haohaoxuexi.iteye.com/blog/2121782 页面缓存 目录 1       SimplePageCachingFilter 1.1      calculate ...

  7. fork安全的gettid高效实现

    进程有id,可以通过getpid()获得,线程也有id,但是glibc没有提供封装.需要自己发出系统调用.在关键路径,系统调用还是对性能有影响的.因此我们可以想到类似glibc对getpid做的cac ...

  8. Android开源框架源码分析:Okhttp

    一 请求与响应流程 1.1 请求的封装 1.2 请求的发送 1.3 请求的调度 二 拦截器 2.1 RetryAndFollowUpInterceptor 2.2 BridgeInterceptor ...

  9. Vue音乐项目笔记(五)

    1.搜索列表的点击删除.删除全部的交互事件 https://blog.csdn.net/weixin_40814356/article/details/80496097 seach组件中放search ...

随机推荐

  1. Plupload使用API

    Plupload有以下功能和特点: 1.拥有多种上传方式:HTML5.flash.silverlight以及传统的<input type=”file” />.Plupload会自动侦测当前 ...

  2. php第三节(运算符)

    <?php //算术运算符 + - * / % //++ 前加加 先做加运算后座赋值运算 后加加 先做赋值运算后座加运算 //-- 前减减 先做加运算后座赋值运算 后减减 先做赋值运算后座加运算 ...

  3. 『ACM C++』 PTA 天梯赛练习集L1 | 001-006

    应师兄要求,在打三月底天梯赛之前要把PTA上面的练习集刷完,所以后面的时间就献给PTA啦~ 后面每天刷的题都会把答案代码贡献出来,如果有好的思路想法也会分享一下~ 欢迎大佬提供更好的高效率算法鸭~ - ...

  4. python写爬虫的弯路

    一开始按照视频上的找了笔趣阁的网站先爬一部小说, 找了<遮天>,但是章节太多,爬起来太慢, 就换了一个几十章的小说. 根据视频里的去写了代码, 在正则表达式哪里出了很大的问题. from ...

  5. ABAP术语-Data Transfer

    Data Transfer 原文:http://www.cnblogs.com/qiangsheng/archive/2008/01/22/1048286.html The entire proces ...

  6. 今天看到的一篇文章:一位资深程序员大牛给予Java初学者的学习路线建议

    一位资深程序员大牛给予Java初学者的学习路线建议 持续学习!

  7. Spring Boot2.4双数据源的配置

    相较于单数据源,双数据源配置有时候在数据分库的时候可能更加有利 但是在参考诸多博客以及书籍(汪云飞的实战书)的时候,发现对于spring boot1.X是完全没问题的,一旦切换到spring boot ...

  8. 主流浏览器内核,以及CSS3前缀识别码

    现在国内常见的浏览器有:IE.Firefox.QQ浏览器.Safari.Opera.Google Chrome.百度浏览器.搜狗浏览器.猎豹浏览器.360浏览器.UC浏览器.遨游浏览器.世界之窗浏览器 ...

  9. 做 JAVA 开发,怎能不用 IDEA!

    用了 IDEA,感觉不错.决定弃用 Eclipse 入门教程: www.cnblogs.com/yangyquin/p/5285272.html

  10. 怎么用Python Flask模板jinja2在网页上打印显示16进制数?

    问题:Python列表(或者字典等)数据本身是10进制,现在需要以16进制输出显示在网页上 解决: Python Flask框架中 模板jinja2的If 表达式和过滤器 假设我有一个字典index, ...