加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

缓存 – 有没有办法在Microsoft Enterprise Library中创建多个Ca

发布时间:2020-12-14 03:57:48 所属栏目:Windows 来源:网络整理
导读:我们正在尝试迁移以使用Microsoft Enterprise Library – 缓存块.但是,缓存管理器初始化似乎与配置文件条目紧密相关,我们的应用程序即时创建内存“容器”.无论如何,使用预先配置的值集(仅限内存)可以动态实例化高速缓存管理器的实例. 解决方法 Enterprise Li
我们正在尝试迁移以使用Microsoft Enterprise Library – 缓存块.但是,缓存管理器初始化似乎与配置文件条目紧密相关,我们的应用程序即时创建内存“容器”.无论如何,使用预先配置的值集(仅限内存)可以动态实例化高速缓存管理器的实例.

解决方法

Enterprise Library 5具有 fluent configuration,可以轻松地以编程方式配置块.例如:

var builder = new ConfigurationSourceBuilder();

builder.ConfigureCaching()
       .ForCacheManagerNamed("MyCache")
       .WithOptions
         .UseAsDefaultCache()
         .StoreInIsolatedStorage("MyStore")
         .EncryptUsing.SymmetricEncryptionProviderNamed("MySymmetric");

var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current 
  = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);

不幸的是,您似乎需要一次配置整个块,因此您无法动态添加CacheManagers. (当我在同一个构建器上调用ConfigureCaching()两次时会抛出异常.)您可以创建一个新的ConfigurationSource,但之后会丢失以前的配置.也许有一种方法可以检索现有配置,修改它(例如添加一个新的CacheManager)然后替换它?我找不到办法.

另一种方法是直接使用缓存类.

以下示例使用Caching类来实例化两个CacheManager实例并将它们存储在静态Dictionary中.不需要配置,因为它没有使用容器.我不确定这是个好主意 – 对我来说感觉有点不对劲.这很简陋,但希望有所帮助.

public static Dictionary<string,CacheManager> caches = new Dictionary<string,CacheManager>();

static void Main(string[] args)
{
    IBackingStore backingStore = new NullBackingStore();
    ICachingInstrumentationProvider instrProv = new CachingInstrumentationProvider("myInstance",false,new NoPrefixNameFormatter());

    Cache cache = new Cache(backingStore,instrProv);
    BackgroundScheduler bgScheduler = new BackgroundScheduler(new ExpirationTask(null,instrProv),new ScavengerTask(0,int.MaxValue,new NullCacheOperation(),instrProv);

    CacheManager cacheManager = new CacheManager(cache,bgScheduler,new ExpirationPollTimer(int.MaxValue));
    cacheManager.Add("test1","value1");
    caches.Add("cache1",cacheManager);

    cacheManager = new CacheManager(new Cache(backingStore,new ExpirationPollTimer(int.MaxValue));
    cacheManager.Add("test2","value2");            
    caches.Add("cache2",cacheManager);

    Console.WriteLine(caches["cache1"].GetData("test1"));
    Console.WriteLine(caches["cache2"].GetData("test2"));
}

public class NullCacheOperation : ICacheOperations
{
    public int Count { get { return 0; } }
    public Hashtable CurrentCacheState { get { return new System.Collections.Hashtable(); } }
    public void RemoveItemFromCache(string key,CacheItemRemovedReason removalReason) {}
}

如果到期和清理策略相同,那么最好创建一个CacheManager然后使用一些智能密钥名来表示不同的“容器”.例如.密钥名称可以采用“{container name}:{item key}”格式(假设冒号不会出现在容器或密钥名称中).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读