解决ASP.NET中缓存被覆盖的问题

众所周知, ASP.NET的System.Web命名空间下的缓存可以用来保存一段时间的数据

因此, 在项目中我们可能利用它来保存一些缓存数据.

因此, 很多人写了这样的工具类来保存和加载缓存

保存缓存:

public static void SetCache(string CacheKey, object objObject)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(key, objObject);
        }
public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(key, objObject, null, absoluteExpiration, slidingExpiration);
        }

加载缓存:

public static object GetCache(string CacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            return objCache[key];
        }

但是这样就引入了一个问题:

如果多个用户同时访问,缓存是不是会被覆盖呢,或者同一个用户打开不同的窗口,缓存是否会被覆盖呢?

经过测试,答案是肯定的.

 

那么,如何解决这个问题呢?

我们想到了sessionId, 那个是一个用户的会话的概念.

因此,我们只要引入一个工具类,用来获取用户的会话id

public static string GetSessionId()
 {
     return HttpContext.Current.Session.SessionID;
 }

修改后的代码如下

保存缓存:

public static void SetCache(string CacheKey, object objObject)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            string sessionId = Utility.GetSessionId();
            string key = CacheKey + "_" + sessionId;
            objCache.Insert(key, objObject);
        }
public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            string sessionId = Utility.GetSessionId();
            string key = CacheKey + "_" + sessionId;
            objCache.Insert(key, objObject, null, absoluteExpiration, slidingExpiration);
        }

 

加载缓存:

public static object GetCache(string CacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            string sessionId = Utility.GetSessionId();
            string key = CacheKey + "_" + sessionId;
            return objCache[key];
        }

经过测试, 问题解决OK

技术改变世界
原文地址:https://www.cnblogs.com/davidgu/p/2473117.html