码迷,mamicode.com
首页 > 系统相关 > 详细

Cache的封装和使用

时间:2018-08-02 15:04:01      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:text   store   switch   etc   normal   md5   red   sum   task   

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 = 30);

        /// <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 = 600)
        {
            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 = 600)
        {
            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 = 30)
        {
            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 = 30)
        {
            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(1));
                        //添加缓存
                        CacheManager.Add(model.Id.ToString(), model, 3600);
                        //获取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, 3600);
                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 = 0)
        {
            //获取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的封装和使用

标签:text   store   switch   etc   normal   md5   red   sum   task   

原文地址:https://www.cnblogs.com/wangwust/p/9406671.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!