如何在ASP.NET 5 MVC中访问缓存?

时间:2015-07-24 03:14:48

标签: asp.net-core

我正在尝试了解有关ASP.NET 5和新.NET Core的更多信息,并尝试确定是否存在内置内存缓存。

我发现了Microsoft.Framework.Caching.Memory.MemoryCache。 但是可用的文档非常少。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:15)

有两个缓存接口IMemoryCacheIDistributedCacheIDistrbutedCache旨在用于存在共享缓存的云托管方案,共享缓存在应用程序的多个实例之间共享。否则使用IMemoryCache

您可以通过调用以下方法在启动时添加它们:

private static void ConfigureCaching(IServiceCollection services)
{
    // Adds a default in-memory implementation of IDistributedCache, which is very fast but 
    // the cache will not be shared between instances of the application. 
    // Also adds IMemoryCache.
    services.AddCaching();

    // Uncomment the following line to use the Redis implementation of      
    // IDistributedCache. This will override any previously registered IDistributedCache 
    // service. Redis is a very fast cache provider and the recommended distributed cache 
    // provider.
    // services.AddTransient<IDistributedCache, RedisCache>();

    // Uncomment the following line to use the Microsoft SQL Server implementation of 
    // IDistributedCache. Note that this would require setting up the session state database.
    // Redis is the preferred cache implementation but you can use SQL Server if you don't 
    // have an alternative.
    // services.AddSqlServerCache(o =>
    // {
    //     o.ConnectionString = 
    //       "Server=.;Database=ASPNET5SessionState;Trusted_Connection=True;";
    //     o.SchemaName = "dbo";
    //     o.TableName = "Sessions";
    // });
}

IDistributedCache是大多数人想要用来充分利用缓存的一个,但它有一个非常原始的接口(你只能用它来获取/保存字节数组)和很少的扩展方法。有关详细信息,请参阅this问题。

您现在可以将IDistributedCacheIMemoryCache注入您的控制器或服务,并照常使用它们。使用它们非常简单,毕竟它们有点像字典。以下是IMemoryCache

的示例
public class MyService : IMyService
{
    private readonly IDatabase database;
    private readonly IMemoryCache memoryCache;

    public MyService(IDatabase database, IMemoryCache memoryCache)
    {
        this.database = database;
        this.memoryCache = memoryCache;
    }

    public string GetCachedObject()
    {
        string cachedObject;
        if (!this.memoryCache.TryGetValue("Key", out cachedObject))
        {
            cachedObject = this.database.GetObject();
            this.memoryCache.Set(
                "Key", 
                cachedObject, 
                new MemoryCacheEntryOptions()
                {
                    SlidingExpiration = TimeSpan.FromHours(1)
                });
        }

        return cachedObject;
    }
}

答案 1 :(得分:4)