如何使用EnterpriseLibrary缓存将到期时间设置为1分钟

时间:2013-01-10 07:47:50

标签: c# asp.net enterprise-library

我使用EnterpriseLibrary cacheManager

<cacheManagers>
  <add name="NonExperimentalAppsCache" type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null" expirationPollFrequencyInSeconds="60" maximumElementsInCacheBeforeScavenging="10000" numberToRemoveWhenScavenging="100" backingStoreName="Null Storage" />
</cacheManagers>

我希望练习时间为1分钟(绝对,不会在evey缓存触摸时刷新) 我怎样才能做到这一点?因为现在它可以将数据保存更长时间。

我在缓存上使用Repository

    public static List<string> GetAllNonExperimentalAppsNames()
    {
        List<string> nonExperimentalAppsNames = NonExperimentalAppsCacheManager.Get();

        if (nonExperimentalAppsNames == null)
        {
            //was not found in the cache
            nonExperimentalAppsNames = GetAllNonExperimentalAppsNamesFromDb();

            if (nonExperimentalAppsNames != null)
            {
                NonExperimentalAppsCacheManager.Set(nonExperimentalAppsNames);
            }
            else
            {
                mApplicationLogger.Info(string.Format("GetAllNonExperimentalAppsNames:: nonExperimentalAppsNames list is null"));
            }
        }
        return nonExperimentalAppsNames;
    }

...

internal static class NonExperimentalAppsCacheManager
{
    private const string NONEXPERIMENTALAPPS = "NonExperimentalApps";

    private static readonly ICacheManager nonExperimentalAppsCache = CacheFactory.GetCacheManager("NonExperimentalAppsCache");

    internal static List<String> Get()
    {
        return nonExperimentalAppsCache[NONEXPERIMENTALAPPS] as List<String>;
    }

    internal static void Set(List<String> settings)
    {
        nonExperimentalAppsCache.Add(NONEXPERIMENTALAPPS, settings);
    }
}

1 个答案:

答案 0 :(得分:2)

向缓存添加项目时指定绝对过期时间:

internal static void Set(List<String> settings)
{
    nonExperimentalAppsCache.Add(NONEXPERIMENTALAPPS, settings, 
        CacheItemPriority.Normal, null, new AbsoluteTime(TimeSpan.FromMinutes(1)));
}

到期会导致项目从缓存中删除。你可以自己刷新它(你可以用ICacheItemRefreshAction来做)。如果在将项目添加到缓存中时指定了1分钟的到期时间,但到期池频率为10分钟,则除非您尝试访问该项目,否则在10分钟之后该项目不会从缓存中删除。如果在项目“已过期”但仍在缓存中时调用Get()(因为后台进程尚未运行),则该项将从缓存中删除并返回null。

我建议您阅读Design of the Caching Application Block以获取有关内部设计的更多讨论。