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

How to access cache in ASP.NET 5 MVC?

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

我发现了 Microsoft.Framework.Caching.Memory.MemoryCache。 然而,可用的文档很少。

如有任何帮助,我们将不胜感激。

这是一个 MemoryCache 示例:https://github.com/aspnet/Caching/tree/dev/samples/MemoryCacheSample

更多样本:https://github.com/aspnet/Caching/tree/dev/samples

有两个缓存接口,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 是大多数人想要用来充分利用缓存的一种,但它有一个非常原始的接口(你只能使用它 get/save 字节数组)并且很少扩展方法。有关详细信息,请参阅 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;
    }
}