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. React中需要多个倒计时的问题

    最近有一个需求是做一个闪购列表,列表中每一个商品都有倒计时,如果每一个倒计时都去生成一个setTimeout的话,一个页面就会有很多定时器,感觉这种做法不是非常好,于是换了一个思路. 思路是这样的,一 ...

  2. SPOJ8222 NSUBSTR - Substrings(后缀自动机)

    You are given a string S which consists of 250000 lowercase latin letters at most. We define F(x) as ...

  3. 微信订阅号 获取用户基本信息,登录及 php

    <?php //echo file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_cr ...

  4. Sql Server 查看存储过程最后修改时间

    Sql Server 查看存储过程最后修改时间 select * from sys.procedures order by modify_date desc

  5. 爬虫——BeautifulSoup4解析器

    BeautifulSoup用来解析HTML比较简单,API非常人性化,支持CSS选择器.Python标准库中的HTML解析器,也支持lxml的XML解析器. 其相较与正则而言,使用更加简单. 示例: ...

  6. Cygwin安装篇,windows平台上运行的类UNIX模拟环境

    1.虚拟光驱的安装 虚拟光驱下载 一路下一步,不再阐述,这些广告选项不要选 2.安装文档,双击ISO文档 ISO下载地址 链接:http://pan.baidu.com/s/1miFVCYO 密码:z ...

  7. 【vlan-trunk和802.1q子接口配置】

    根据项目需求,搭建好拓扑图如下: 配置sw1的g1/0/3的/trunk,把g1/0/1和g1/0/2分别加入vlan 10 和 vlan 20 配置sw1的g1/0/3的/trunk,把g1/0/1 ...

  8. MySQL wait_timeout参数修改

    MySQL wait_timeout参数修改问题,可能经常会有DBA遇到过,下面就试验一下并看看会有什么现象. wait_timeout分为global级及session级别,如未进行配置,默认值为2 ...

  9. PublicCMS 网站漏洞 任意文件写入并可提权服务器权限

    PublicCMS是目前网站系统中第一个采用JAVA架构 TOMCAT+Apcche+Mysql数据库架构的CMS网站,开源,数据承载量大,可以承载到上千万的数据量,以及用户的网站并发可达到上千万的P ...

  10. oracle 数据被修改怎么修复?(闪回)

    数据被删除 或者 update 的时候忘记勾选where 限制条件,数据全部更新了?  怎么办? 要跑路了? NO !!! 看下面,迅速帮你闪回数据! demo sql: 1. SELECT * FR ...