给自己看的Cache,三段代码
此篇是我记录代码的一个草稿,不是一篇正式的博文,误点的别介意啊。
公司的框架中Cache实现文件:
(1)CacheUtil.cs
using System.Collections.Generic;
using System.Linq;
using Modules;
using ORM; namespace Console
{
public static class CacheUtil
{
private const string LoginUserKey = "CacheKey-LoginUserCacheKey";
private const string SerializedLimitedMenusKey = "CacheKey-SerializedLimitedMenusKey";
private const string AllFuncsKey = "CacheKey-AllFuncsKey";
private const string LimitedFuncsKey = "CacheKey-LimitedFuncsKey"; /// <summary>
/// 获取或设置当前登录用户
/// </summary>
public static User LoginUser
{
get { return WebCache.GetCache(LoginUserKey) as User; }
set { WebCache.SetCache(LoginUserKey, value); }
} /// <summary>
/// 获取用户是否登录的状态
/// </summary>
public static bool IsLogin
{
get { return LoginUser != null; }
} /// <summary>
/// 获取有权限的菜单
/// </summary>
private static IList<Menu> GetLimitedMenus()
{
var isAdmin = LoginUser.IsAdmin;
using (var context = new MyDbContext())
{
IQueryable<Menu> menus = context.Menus;
if (isAdmin) return menus.OrderByDescending(x => x.OrderNumber).ToList();
var menuIds =
(from ur in context.UserRoles
join rm in context.RoleMenus on ur.RoleId equals rm.RoleId
where ur.UserId == LoginUser.Id
select rm.MenuId);
menus = menus.Where(x => menuIds.Contains(x.Id));
return menus.OrderByDescending(x => x.OrderNumber).ToList();
}
} private static IList<Menu> GetSerializedLimitedMenus()
{
var list = new List<Menu>();
var limitedMenus = GetLimitedMenus();
for (var i = limitedMenus.Count - ; i >= ; i--)
{
if (limitedMenus[i].ParentId.HasValue) continue;
list.Add(limitedMenus[i]);
limitedMenus.RemoveAt(i);
}
foreach (var item in list)
{
FeatchChildren(item, limitedMenus);
}
return list;
} private static void FeatchChildren(Menu menu, IList<Menu> menus)
{
if (!menus.Any()) return;
for (var i = menus.Count - ; i >= ; i--)
{
if (!menus[i].ParentId.Equals(menu.Id)) continue;
menu.Children.Add(menus[i]);
menus.RemoveAt(i);
}
if (!menu.Children.Any()) return;
foreach (var child in menu.Children)
{
FeatchChildren(child, menus);
}
} /// <summary>
/// 获取经过序列化的有权限的菜单
/// </summary>
public static IList<Menu> SerializedLimitedMenus
{
get
{
var serializedLimitedMenus = WebCache.GetCache(SerializedLimitedMenusKey) as IList<Menu>;
if (serializedLimitedMenus != null) return serializedLimitedMenus;
serializedLimitedMenus = GetSerializedLimitedMenus();
WebCache.SetCache(SerializedLimitedMenusKey, serializedLimitedMenus);
return serializedLimitedMenus;
}
} /// <summary>
/// 获取拥有权限的菜单上的所有功能
/// </summary>
public static IList<Func> AllFuncs
{
get
{
var allFuncs = WebCache.GetCache(AllFuncsKey) as IList<Func>;
if (allFuncs != null) return allFuncs;
using (var context = new MyDbContext())
{
allFuncs = context.Funcs.ToList().Where(x => !string.IsNullOrWhiteSpace(x.FuncCode)).ToList();
WebCache.SetCache(AllFuncsKey, allFuncs);
}
return allFuncs;
}
} /// <summary>
/// 拥有权限的功能列表
/// </summary>
public static IList<Func> LimitedFuncs
{
get
{
var limitedFuncs = WebCache.GetCache(LimitedFuncsKey) as IList<Func>;
if (limitedFuncs != null) return limitedFuncs;
var isAdmin = LoginUser.IsAdmin;
using (var context = new MyDbContext())
{
IQueryable<Func> funcs = context.Funcs;
if (!isAdmin)
{
var funcIds =
(from ur in context.UserRoles
join rm in context.RoleFuncs on ur.RoleId equals rm.RoleId
where ur.UserId == LoginUser.Id
select rm.FuncId);
funcs = funcs.Where(x => funcIds.Contains(x.Id));
} limitedFuncs = funcs.ToList();
}
WebCache.SetCache(LimitedFuncsKey, limitedFuncs);
return limitedFuncs;
}
} public static IList<Func> GetForbiddenFuncs()
{
return LoginUser == null
? AllFuncs
: AllFuncs.Where(x => LimitedFuncs.All(y => y.Id != x.Id)).ToList();
}
}
}
(2)WebCache.cs(核心)
using System;
using System.Web;
using System.Web.Caching;
using Common; namespace Console
{
/// <summary>
/// 缓存操作类
/// </summary>
public class WebCache
{
#region 私有变量 private const string UserIdentifyKey = "CacheUserIdentifyKey"; #endregion #region 公共方法 /// <summary>
/// 获取缓存
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
public static object GetCache(string key)
{
return GetUserCache()[key];
} /// <summary>
/// 设置缓存
/// </summary>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <returns></returns>
public static bool SetCache(string key, object value)
{
try
{
var userCache = GetUserCache();
userCache[key] = value;
return true;
}
catch
{
return false;
}
} /// <summary>
/// 清空缓存
/// </summary>
/// <returns></returns>
public static bool ClearCache()
{
try
{
// 只清除缓存内容
// GetUserCache().Clear(); // 直接从Cache里移除
var identify = GetUserIdentify();
HttpContext.Current.Cache.Remove(identify);
return true;
}
catch
{
return false;
}
} /// <summary>
/// 移除缓存
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
public static bool RemoveCache(string key)
{
try
{
GetUserCache().Remove(key);
return true;
}
catch
{
return false;
}
} #endregion #region 私有方法 private static string GetUserIdentify()
{
if (HttpContext.Current.Session[UserIdentifyKey] != null)
return HttpContext.Current.Session[UserIdentifyKey].ToString();
var identify = Guid.NewGuid().ToString();
HttpContext.Current.Session[UserIdentifyKey] = identify;
return identify;
} private static UserCache GetUserCache()
{
var identify = GetUserIdentify();
if (HttpContext.Current.Cache.Get(identify) == null)
{
HttpContext.Current.Cache.Insert(identify, new UserCache(), null, Cache.NoAbsoluteExpiration,
new TimeSpan(, , ), CacheItemPriority.High, CacheRemovedCallback);
}
return HttpContext.Current.Cache.Get(identify) as UserCache;
} /// <summary>
/// 缓存被移除时触发
/// </summary>
/// <param name="key">被移除的缓存的key</param>
/// <param name="value">被移除的缓存的值</param>
/// <param name="reason">移除原因</param>
private static void CacheRemovedCallback(string key, object value, CacheItemRemovedReason reason)
{
// 缓存被移除时执行的操作
// 如果是手动移除,则不处理
//if (reason == CacheItemRemovedReason.Removed)
// return; // 此处访问页面会报错,暂时注释掉
// ShowNotification(MessageType.Warning, "警告", "由于您太久没操作页面已过期,请重新登录!", true);
} #endregion
}
}
(3)UserCache.cs
using System.Collections.Generic; namespace Common
{
public class UserCache
{
private readonly Dictionary<string, object> cacheDictionary = new Dictionary<string, object>();
private readonly object lockObj = new object(); /// <summary>
/// 索引器
/// </summary>
/// <param name="key">key</param>
/// <returns>缓存对象</returns>
public object this[string key]
{
get
{
lock (lockObj)
{
return cacheDictionary.ContainsKey(key) ? cacheDictionary[key] : null;
}
}
set
{
lock(lockObj)
{
if (cacheDictionary.ContainsKey(key))
{
cacheDictionary[key] = value;
}
else
{
cacheDictionary.Add(key, value);
}
}
}
} public void Remove(string key)
{
lock (lockObj)
{
if(cacheDictionary.ContainsKey(key))
{
cacheDictionary.Remove(key);
}
}
} public void Clear()
{
lock(lockObj)
{
cacheDictionary.Clear();
}
}
}
}
给自己看的Cache,三段代码的更多相关文章
- 写在最前面 - 《看懂每一行代码 - kubernetes》
我要写什么 <看懂每一行代码 - kubernetes>会包含k8s整个项目的源码解析,考虑到门槛问题,在开始分析k8s之前我会通过一些更低难度的golang开源项目讲解来帮助大家提升go ...
- SDRAM的初始化与刷新操作---看时序图写代码
SDRAM的初始化与刷新操作---看时序图写代码 1.SDRAM的常见操作 2.初始化就是配置SDRAM 3.SDRAM初始化时序 时序解释如下: 4.刷新操作
- 还看不懂同事的代码?超强的 Stream 流操作姿势还不学习一下
Java 8 新特性系列文章索引. Jdk14都要出了,还不能使用 Optional优雅的处理空指针? Jdk14 都要出了,Jdk8 的时间处理姿势还不了解一下? 还看不懂同事的代码?Lambda ...
- 如何使用 js 写一个正常人看不懂的无聊代码
如何使用 js 写一个正常人看不懂的无聊代码 代码质量, 代码可读性, 代码可维护性, clean code WAT js WTF https://www.destroyallsoftware.com ...
- 《明解c语言》已看完,练习代码此奉上
2016年9月20日至2016年11月12日,从学校图书馆借来的<明解c语言>看完了. 大三第一个学期,前8周,有c语言程序设计的课.课本是学校里的老师编写出版的,为了压缩空间,减少页面, ...
- c++聪聪看书(满分代码)
聪聪是一个善良可爱.睿智聪慧的好孩子.聪聪喜欢看书,这一天她在看一本书时看到了这样一个问题:给你一个正整数n,你要将它分成若干个自然数Ai的和的形式,并且使得这若干个自然数Ai的乘积尽量大,并输出最大 ...
- 还看不懂同事的代码?Lambda 表达式、函数接口了解一下
当前时间:2019年 11月 11日,距离 JDK 14 发布时间(2020年3月17日)还有多少天? // 距离JDK 14 发布还有多少天? LocalDate jdk14 = LocalDate ...
- 自学Python编程的第五天(希望有IT大牛帮我看最下面的代码)----------来自苦逼的转行人
2019-09-15-15:40:24 今天没有学知识,是一个一周总结,把这一周学的知识总结一遍,然后把做过的练习题再做一遍 看是否还会有再出现同样的错误,而且还可以知道有哪些知识点没有掌握好,可以把 ...
- Android中活动的最佳实践(如何很快的看懂别人的代码activity)
这种方法主要在你拿到别人的代码时候很多activity一时半会儿看不懂,用了这个方法以后就可以边实践操作就能够知道具体哪个activity是干什么用的 1.新建一个BaseActivity的类,让他继 ...
随机推荐
- linux jar/war包 后台运行
1. 基础版,当前ssh窗口锁定,按CTRL+C打断程序运行:或关闭窗口,程序退出 java -jar flowable-modeler.war 2. 改进版,当前ssh窗口不锁定,窗口关闭时,程序终 ...
- 一种SpaceClaim抽取流道的方法——利用缺失的面功能
针对不干净的几何,内部存在诸多碎面小缝隙,采用此方法可能会有较好的效果,不过需要耐心. 测试几何需要SpaceClaim19.0以上软件可以打开,下载链接: https://pan.baidu.com ...
- [技术博客]微信小程序开发中遇到的两个问题的解决
IDE介绍 微信web开发者工具 前端语言 微信小程序使用的语言为wxml和wss,使用JSON以及js逻辑进行页面之间的交互.与网页的html和css略有不同,微信小程序在此基础上添加了自己的改进, ...
- mstar 平台I2C 配置
芯片的pin 脚可以用作不同的功能,总结一句就是外设进行状态和数据交换. 最常用的是作为GPIO,设置为输出模式时,通过高低电平来控制一些外围设置:// 如LED,屏的电源,背光的开关,功放的静音等等 ...
- Learning to Track Any Object
Learning to Track Any Object 2019-10-28 12:14:49 Paper: https://arxiv.org/abs/1910.11844 1.
- Windows curl开启注意事项
php.ini 开启curl扩展 设置有时候开启之后,curl还是不行:将php目录下的libssh2.dll复制到apache/bin下.(基本上可以成功) 如果没有开启成功,将php安装目录下 ...
- odoo开发笔记 -- odoo快速开发技巧
1. 需求分析到位 2. 系统对接,角色用例,数据串接 ---确定,轻易不可变更 3. 业务流程拆分细化 出图--开发人员理解的地步 4. 数据模型建立 --对应角色用例 5. 确立开发计划,划分功能 ...
- mybatis如何接受map类型的参数
Mybatis传入参数类型为Map mybatis更新sql语句: ? 1 2 3 4 5 6 7 8 9 <update id="publishT00_notice" ...
- 国内pip源及pip命令
更换PIP源 PIP源在国外,速度慢,可以更换为国内源,以下是国内一些常用的PIP源. 豆瓣(douban) http://pypi.douban.com/simple/ (推荐) 清华大学 http ...
- 123456123456----updateV#%#6%#%---pinLv###1%%%----com.zzj.CarCleanGame567---前show后广--儿童洗车-222222
com.zzj.CarCleanGame567---前拼show后广--儿童洗车-