दो कैशिंग इंटरफेस, IMemoryCache
और IDistributedCache
रहे हैं। IDistrbutedCache
क्लाउड होस्टेड परिदृश्यों में उपयोग करने का इरादा है जहां एक साझा कैश है, जिसे एप्लिकेशन के कई उदाहरणों के बीच साझा किया जाता है। अन्यथा 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 अंक देखें।
अब आप अपने नियंत्रक या सेवा में IDistributedCache
या IMemoryCache
इंजेक्ट कर सकते हैं और उन्हें सामान्य के रूप में उपयोग कर सकते हैं। उनका उपयोग करना बहुत आसान है, वे सभी के बाद शब्दकोशों की तरह थोड़ा सा हैं। यहां 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;
}
}
स्रोत
2015-07-24 09:25:23
ये नमूने सभी कंसोल ऐप्स हैं। मुझे नहीं लगता कि @ sam360 – DevHawk