代码改变世界

浅谈缓存的设计与使用注意项(上)

2010-12-28 00:13  姜 萌@cnblogs  阅读(1749)  评论(0编辑  收藏  举报

memory cache + backing store

enterprise libiary中的caching block

在微软pattern&practise团队发布的enterprise library5版本中带有一个caching block,这个缓存块为我们提供了缓存数据大一些列方法。其架构如下图(这里再说明一下:caching block以后会被整合进.net framework之中,enterlib5的后续版本会将caching block剔除):

image

caching block采用的是“内存缓存+backing store”结构(不过backing store是可选的),程序启动时缓存被加载到memory cache,也就是进程内存中(具体有两种加载策略,positive和reactive),当我们通过key调用对应的缓存项时首先在内存中查找,如果没有就去backing store查找,对于已经夹在到内存中的缓存项只有在其过期或者手动remove才会剔除而不会因为backing store的变化被主动通知到,这个特点会影响到多进程实例/同一进程不同程序域对backing store访问问题,这部分将在下篇提到。

扩展backing storeage

backing store有三种形式:

Isolated storage

缓存到隔离存储中

Database cache storage

缓存到数据库中

Custom backing storage

自行实现IBackingStore

对于一般情形,我们在客户端使用IsolatedStorage作为backing store在服务器端使用Database cache storage作为backing store比较合适,如果您需要更高的效能,可以自定义实现IBackingStore,比如将MemoryCached与缓存数据库相结合作为IBackingStore。

image

只需要实现IBackingStorage如下:

public class MixedBackingStorage :IBackingStore
    {
        [Dependency]
        
public IBackingStore DbObjectProvider
        {
            
get;
            
set;
        }
        [Dependency]
        
public IBackingStore MemoryCachedProvider
        {
            
get;
            
set;
        }

        
public void Add(CacheItem newCacheItem)
        {
            
if (MemoryCachedProvider.IsAvailable)
            {
                MemoryCachedProvider.Add(newCacheItem);
            }
            
else if (DbObjectProvider.IsAvailable)
            {
                DbObjectProvider.Add(newCacheItem);
            }
            
else
                
throw new BackCachingSourceException();
        }

        
public int Count
        {
            
get
            {
                
return MemoryCachedProvider.Count + DbObjectProvider.Count;
            }
        }

        
public void Flush()
        {
            MemoryCachedProvider.Flush();
            DbObjectProvider.Flush();
        }

        
public System.Collections.Hashtable Load()
        {;
            
return MemoryCachedProvider.Load();
        }

        
public void Remove(string key)
        {
            
if (MemoryCachedProvider.Remove(key))
                
return;
            
if (DbObjectProvider.Remove(key))
                
return;
        }

        
public void UpdateLastAccessedTime(string key, DateTime timestamp)
        {
            MemoryCachedProvider.UpdateLastAccessedTime(key, timestamp);
            DbObjectProvider.UpdateLastAccessedTime(key, timestamp);
        }

        
public void Dispose()
        {
            MemoryCachedProvider.Dispose();
            DbObjectProvider.Dispose();
        }
    }