Asp.net core 如何在ASP.NET 5 MVC中访问缓存?
我试图了解更多关于ASP.NET 5和新的.NET内核的信息,并试图找出是否有内置内存缓存 我发现了有关Microsoft.Framework.Caching.Memory.MemoryCache的信息。 但是,可用的文档非常少Asp.net core 如何在ASP.NET 5 MVC中访问缓存?,asp.net-core,Asp.net Core,我试图了解更多关于ASP.NET 5和新的.NET内核的信息,并试图找出是否有内置内存缓存 我发现了有关Microsoft.Framework.Caching.Memory.MemoryCache的信息。 但是,可用的文档非常少 任何帮助都将不胜感激。这是一个MemoryCache示例: 更多示例:有两个缓存接口,IMemoryCache和IDistributedCache。IDistrButterCache用于云托管场景,其中存在共享缓存,该缓存在应用程序的多个实例之间共享。否则,请使用IMe
任何帮助都将不胜感激。这是一个MemoryCache示例:
更多示例:有两个缓存接口,
IMemoryCache
和IDistributedCache
。IDistrButterCache
用于云托管场景,其中存在共享缓存,该缓存在应用程序的多个实例之间共享。否则,请使用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";
// });
}
这非常有用,但我对数据库缓存不太感兴趣。对我来说这是无用的。如果数据已经存储在DB中,并且我支付了访问它的高昂成本,那么在DB中缓存它又有什么意义呢!我同意,不要使用SQL Server。使用内存缓存是最快的选择,但是如果您有多个站点实例呢?这就是Redis缓存的用武之地。Redis速度非常快,正是出于这些目的。如果您使用
IDistributedCache
,那么如果由于用户众多而需要站点的另一个实例,那么您的站点将变得可扩展。SQL Server 2016现在还具有内存模式,因此速度更快,现在是一个可行的缓存选项。这些示例都是控制台应用程序。我不认为这就是@sam360想要的
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;
}
}