4.3 可配置的分布式缓存(下)

上节,我们说明了封装分布式缓存的接口、配置以及在startup中的注册方式。下面的,我们具体介绍下,分布式缓存的具体实现。

第一个实现,将本地缓存作为分布式缓存,主要用于没有分布式缓存的情况,这样就可以不修改程序的情况下直接使用本地缓存。

 1     public class DefaultCacheHandler : BaseCacheHandler
 2     {
 3         private IDistributedCache memoryCache;
 4 
 5         public DefaultCacheHandler(CachingConfigInfo configInfo) : base(configInfo)
 6         {
 7             this.memoryCache = new MemoryDistributedCache(new MemoryCache(new MemoryCacheOptions()));
 8         }
 9 
10         protected override IDistributedCache _Cache
11         {
12             get
13             {
14                 return this.memoryCache;
15             }
16         }
17     }

 

第二个实现,使用redis作为分布式缓存。

 1     public class RedisCacheHandler : BaseCacheHandler
 2     {
 3         private IDistributedCache _RedisCache;
 4 
 5         public RedisCacheHandler(CachingConfigInfo configInfo) : base(configInfo)
 6         {
 7             IOptions<RedisCacheOptions> optionsAccessor = new RedisCacheOptions();
 8 
 9             optionsAccessor.Value.Configuration = string.Join(",", _ConfigInfo.Servers.Select(s => s.HostName + ":" + s.Port));
10             optionsAccessor.Value.InstanceName = "Runtime";
11 
12             _RedisCache = new RedisCache(optionsAccessor);
13         }
14 
15         protected override IDistributedCache _Cache
16         {
17             get
18             {
19                 return _RedisCache;
20             }
21         }
22     }

 

如果想使用Memcached等缓存,具体做法是,首先根据IDistributedCache接口实现对于memcached的存取,然后参照根据以上实现BaseCacheHandler类即可。如何根据IDistributedCache接口实现对于memcached的存取,这是一个难点,不过如果之前使用过.net 访问memcached的时候,应该对Enyim.memcached不陌生吧。博客园使用.net core改写了Enyim.memcached,具体请见.NET跨平台之旅:基于.NET Core改写EnyimMemcached,实现Linux上访问memcached缓存

其实从这个类库的源代码我们可以发现,MemcachedClient是IDistributedCache接口的实现,因此这个我们拿过来直接使用就行,剩下再利用MemcachedClient编写一个实现BaseCacheHandler类就万事大吉了:)

面向云的.net core开发框架目录

 

MemcachedClient
posted @ 2016-10-31 18:59  BenDan2002  阅读(1231)  评论(1编辑  收藏  举报