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

公司的框架中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. [原创]App弱网测试方法介绍

    [原创]App弱网测试方法介绍 1 什么是弱网? 弱网就是在非正常网络状态下,用户在访问网络时遭遇到网络延迟或是丢包,造成使用产品时用户体验不佳或反感的场景. 2   为什么要进行弱网测试 简而方之, ...

  2. 方法型混淆js代码

    const fs = require('fs'); const acorn = require('acorn'); const walk = require("acorn-walk" ...

  3. SpringBoot激活profiles

    多环境是最常见的配置隔离方式之一,可以根据不同的运行环境提供不同的配置信息来应对不同的业务场景,在SpringBoot内支持了多种配置隔离的方式,可以激活单个或者多个配置文件. 激活Profiles的 ...

  4. python 文字转语音

    # coding=utf-8 import pyttsx3 text='I love you 韩长菊' voice=pyttsx3.init() voice.say(text) voice.runAn ...

  5. Gradle插件和Gradle对应表

    Gradle插件build.gradle文件的buildscript Gradlegradle/wrapper/gradle-wrapper.properties文件 AndroidStudio版本 ...

  6. Java基础 awt Graphics2D 生成矩形图片并向内写入字符串

        JDK :OpenJDK-11      OS :CentOS 7.6.1810      IDE :Eclipse 2019‑03 typesetting :Markdown   code ...

  7. Roberts算子

    https://blog.csdn.net/likezhaobin/article/details/6892176 https://zhuanlan.zhihu.com/p/35032299 Robe ...

  8. “庚武讲堂”(v.gw66.net) 缘起

    转载自: https://v.gw66.net/origin/ 我叫“庚武”,一个从业10余年的程序员,其实我更愿意自称软件工程师或软件设计师.转眼间倏忽十年,从最开始用ASP.net 2.0做网站入 ...

  9. roboware 常见操作和问题

    博客参考:https://blog.csdn.net/u013528298/article/details/88052470 1. build中错误位置定位方式 按住“CTRL”键并点击错误提示的链接 ...

  10. ERROR: CAN'T FIND PYTHON EXECUTABLE "PYTHON", YOU CAN SET THE PYTHON ENV VARIABLE.解决办法

    错误原因:Node.js 在安装模块的时候报错,缺少python环境. 解决办法: 第一种方式: 安装Python及环境变量配置 一定要安装python2.7的版本 环境变量安装可以参考:http:/ ...