码迷,mamicode.com
首页 > Web开发 > 详细

[Architect] ABP(现代ASP.NET样板开发框架)(9) Caching

时间:2016-03-05 23:34:03      阅读:317      评论:0      收藏:0      [点我收藏+]

标签:

本节目录

介绍

Abp提供了1个缓存的抽象.内部使用这个缓存抽象.虽然默认的实现使用MemoryCache,但是可以切换成其他的缓存.

 

ICacheManager

提供缓存的接口为ICacheManager.我们可以注入并使用他.如:

public class TestAppService : ApplicationService
{
    private readonly ICacheManager _cacheManager;

    public TestAppService(ICacheManager cacheManager)
    {
        _cacheManager = cacheManager;
    }

    public Item GetItem(int id)
    {
        //Try to get from cache
        return _cacheManager
                .GetCache("MyCache")
                .Get(id.ToString(), () => GetFromDatabase(id)) as Item;
    }

    public Item GetFromDatabase(int id)
    {
        //... retrieve item from database
    }
}

在上例中,我们注入ICacheManager 并且获得1个名为MyCache的缓存.

 

WARNING: GetCache Method

不要在你的构造函数中使用GetCache方法.如果你的类是transient,这可能会释放Cache.

 

ICache

ICacheManager.GetCache 方法会返回1个ICache.每个Cache都是单例的.在第一次请求时创建,然后一直使用相同的cache实例.所以,我们共享cache在不同的class中.

ICache.Get方法有2个参数:

  • key: 在cache中唯一的字符串.
  • factory: 在给定的key上,未找到对应的item时. Factory method 应该创建并返回对应的item.如果在cache中能找到,则不会调用该Action.

ICache interface also has methods like GetOrDefaultSetRemove and Clear. There are also async versions of all methods.

ICache 接口还提供了一些如 GetOrDefaultSetRemove and Clear的方法.同样提供了所有方法的async版本.

 

ITypedCache

ICache 接口是以string为key,object为value.ITypedCache 包装了ICache提供类型安全,泛型cache.将ICache转为ITypedCache,我们需要使用AsTyped 扩展方法:

ITypedCache<int, Item> myCache = _cacheManager.GetCache("MyCache").AsTyped<int, Item>();

然后我们使用Get方法,就不需要做手动转换.

 

Configuration

默认的cache expire time为60min.这是滑动过期方式.所以当你不使用1个item超过60分钟时,则会自动从缓存中移除.你可以为所有cache或1个cache做配置.

//Configuration for all caches
Configuration.Caching.ConfigureAll(cache =>
{
    cache.DefaultSlidingExpireTime = TimeSpan.FromHours(2);
});

//Configuration for a specific cache
Configuration.Caching.Configure("MyCache", cache =>
{
    cache.DefaultSlidingExpireTime = TimeSpan.FromHours(8);
});

这种代码应该放在module的 PreInitialize 方法中.如上代码中,MyCache 将会有8小时的expire time,而其他的cache有2小时.

你的配置Action只会在第一次请求时调用一次.除了expire time外,还可以自由配置和初始化ICache.

[Architect] ABP(现代ASP.NET样板开发框架)(9) Caching

标签:

原文地址:http://www.cnblogs.com/neverc/p/5210617.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!