解决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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值