此篇是我记录代码的一个草稿,不是一篇正式的博文,误点的别介意啊。

公司的框架中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,三段代码的更多相关文章

  1. 写在最前面 - 《看懂每一行代码 - kubernetes》

    我要写什么 <看懂每一行代码 - kubernetes>会包含k8s整个项目的源码解析,考虑到门槛问题,在开始分析k8s之前我会通过一些更低难度的golang开源项目讲解来帮助大家提升go ...

  2. SDRAM的初始化与刷新操作---看时序图写代码

    SDRAM的初始化与刷新操作---看时序图写代码 1.SDRAM的常见操作 2.初始化就是配置SDRAM 3.SDRAM初始化时序 时序解释如下: 4.刷新操作

  3. 还看不懂同事的代码?超强的 Stream 流操作姿势还不学习一下

    Java 8 新特性系列文章索引. Jdk14都要出了,还不能使用 Optional优雅的处理空指针? Jdk14 都要出了,Jdk8 的时间处理姿势还不了解一下? 还看不懂同事的代码?Lambda ...

  4. 如何使用 js 写一个正常人看不懂的无聊代码

    如何使用 js 写一个正常人看不懂的无聊代码 代码质量, 代码可读性, 代码可维护性, clean code WAT js WTF https://www.destroyallsoftware.com ...

  5. 《明解c语言》已看完,练习代码此奉上

    2016年9月20日至2016年11月12日,从学校图书馆借来的<明解c语言>看完了. 大三第一个学期,前8周,有c语言程序设计的课.课本是学校里的老师编写出版的,为了压缩空间,减少页面, ...

  6. c++聪聪看书(满分代码)

    聪聪是一个善良可爱.睿智聪慧的好孩子.聪聪喜欢看书,这一天她在看一本书时看到了这样一个问题:给你一个正整数n,你要将它分成若干个自然数Ai的和的形式,并且使得这若干个自然数Ai的乘积尽量大,并输出最大 ...

  7. 还看不懂同事的代码?Lambda 表达式、函数接口了解一下

    当前时间:2019年 11月 11日,距离 JDK 14 发布时间(2020年3月17日)还有多少天? // 距离JDK 14 发布还有多少天? LocalDate jdk14 = LocalDate ...

  8. 自学Python编程的第五天(希望有IT大牛帮我看最下面的代码)----------来自苦逼的转行人

    2019-09-15-15:40:24 今天没有学知识,是一个一周总结,把这一周学的知识总结一遍,然后把做过的练习题再做一遍 看是否还会有再出现同样的错误,而且还可以知道有哪些知识点没有掌握好,可以把 ...

  9. Android中活动的最佳实践(如何很快的看懂别人的代码activity)

    这种方法主要在你拿到别人的代码时候很多activity一时半会儿看不懂,用了这个方法以后就可以边实践操作就能够知道具体哪个activity是干什么用的 1.新建一个BaseActivity的类,让他继 ...

随机推荐

  1. Java中的long类型和Long类型比较大小

    Java中我们经常要做一些判断,而对于判断的话,用的最多的便是“>”.“==”.“<”的比较,这里我们进行一个Long类型数据和long类型数据的比较大小的讲解. Java中Long和lo ...

  2. 第01组 Alpha冲刺(1/6)

    队名:007 组长博客: https://www.cnblogs.com/Linrrui/p/11845138.html 作业博客: https://edu.cnblogs.com/campus/fz ...

  3. centOS7开启ssh免密登陆

    一.登陆服务器生成ssh-key 二.把ssh-key复制到被登陆机器上 三.设置权限 root# .ssh 文件夹权限 root# .ssh/authorized_keys 文件权限 四.测试是否正 ...

  4. CT窗宽位宽

    先说一下CT值是什么 CT图像反映的是人体对X射线吸收的系数,但我们关心的是各组织结构的密度差异,即相对密度,如果某组织发生病变,其密度就会发生变化,但由于比较吸收系数非常繁琐,于是亨氏把组织器官对X ...

  5. mvel语法指南[翻译]

    mvel受到了java语法的启发,但是存在一些根本性的差异,mvel旨在使其成为更有效的表达式语言.比如直接支持集合.数组和字符串匹配,正则表达式的运算操作等. mvel2.x有以下几个部分组成:  ...

  6. SVN 从主干合并到分支库

    主干库:平时开发用的库, 分支库:中途需要进行上生产环境的库 分支库的版本从主干库拉过去就行 红色的为分支库. 创建的速度很快. 1.创建好后,在主干库添加一个文件. 2.然后分支库进行合并,这里用e ...

  7. js开启和关闭页面滚动【亲测有效】

    在移动端的页面开发过程中,经常会遇到点击弹框禁止页面滚动的情景,下面就来说下具体的做法... 第一步:构建一个函数 function bodyScroll(event){ event.preventD ...

  8. postgre with递归查询组织路径

    with递归查询组织路径 SELECT r.id, (array_to_string( array( select name from ( with recursive rec as( select ...

  9. k8s记录-k8s部署参考

    一.环境准备 yum -y install epel-release yum -y install wget nmap lsof iotop lrzsz ntpdate tree rm -rf /et ...

  10. FFmpeg 的bug

    发现一个ffmpeg 的bug, 我用老版本的ffmpeg解码播视频,对同样的视频,音频部分得到的是6通道,一直有杂音 周末呢换了新版本的ffmpeg4.2的库,得到是4,6,8三个通道在切换,我修改 ...