Skip to content

पोस्ट

ASP.Net Core में Request Caching को Implement करना

8 जुलाई 2019 • 4 मिनट पढ़ना

ASP.Net Core में Request Caching को Implement करना

एप्लिकेशन के विकास में किसी न किसी बिंदु पर, आमतौर पर काफी जल्दी, आपको एहसास होता है कि एप्लिकेशन धीमी है। कुछ रिसर्च के बाद, समस्या यह होती है कि अनावश्यक रूप से वही डेटा बार-बार retrieve किया जा रहा है, और एक बल्ब जलता है, और आप सोचते हैं: “मुझे कुछ caching की जरूरत है।”

Caching एक अमूल्य pattern है जो database या third party API के redundant calls को eliminate करने के लिए उपयोग किया जाता है। Microsoft time-based caching के लिए IMemoryCache प्रदान करता है, हालांकि कभी-कभी time-based caching वह नहीं होती जिसकी आपको जरूरत होती है। इस article में, हम Request Scoped caching को देखते हैं और यह कैसे हमारे लिए फायदेमंद हो सकती है।

Request caching क्या है? Request caching एक mechanism है जो web request के जीवनकाल के लिए data को cache करती है। Dot-net में, हमारे पास HttpContext.Items collection के साथ कुछ हद तक यह क्षमता थी, हालांकि, HttpContext अपनी injectability के लिए नहीं जाना जाता।

Request Scoped caching के कुछ फायदे हैं: पहला, यह stale data की चिंता को समाप्त करती है। अधिकांश scenarios में, एक request एक सेकंड से कम में execute होती है और जो आमतौर पर data के stale होने के लिए पर्याप्त लंबी नहीं होती। और दूसरा, expiration की चिंता नहीं है क्योंकि data request समाप्त होने पर मर जाता है।

Out of the box, Asp.Net Core में injectable caching नहीं है। जैसा कि पहले उल्लेख किया गया है, HttpContext.Items एक विकल्प है, लेकिन यह एक elegant solution नहीं है।

सौभाग्य से हमारे लिए, ASP.Net Core हमें built-in dependency injection (DI) framework का उपयोग करके एक injectable Request Caching implementation बनाने के लिए tools देता है।

Built-in DI framework में dependencies के लिए तीन lifetimes हैं: Singleton, Scoped, और TransientSingleton application के जीवन के लिए है, Scoped request के जीवन के लिए है और Transient हर request के साथ एक नया instance है।

मैंने IMemoryCache interface के आधार पर एक interface बनाया है ताकि चीजें consistent रहें।

Interface

public interface IRequestCache
{
    /// <summary>
    /// Add the value into request cache. If the key already exists, the value is overwritten.
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <typeparam name="TValue"></typeparam>
    void Add<TValue>(string key, TValue value);

    /// <summary>
    /// Remove the key from the request cache
    /// </summary>
    /// <param name="key"></param>
    void Remove(string key);

    /// <summary>
    /// Retrieve the value by key, if the key is not in the cache then the add func is called
    /// adding the value to cache and returning the added value.
    /// </summary>
    /// <param name="key"></param>
    /// <param name="add"></param>
    /// <typeparam name="TValue"></typeparam>
    /// <returns></returns>
    TValue RetrieveOrAdd<TValue>(string key, Func<TValue> add);

    /// <summary>
    /// Retrieves the value by key. When the key does not exist the default value for the type is returned.
    /// </summary>
    /// <param name="key"></param>
    /// <typeparam name="TValue"></typeparam>
    /// <returns></returns>
    TValue Retrieve<TValue>(string key);
}

Implementation

public class RequestCache : IRequestCache
{
    IDictionary<string, object> _cache = new Dictionary<string, object>();

    /// <summary>
    /// Add the value into request cache. If the key already exists, the value is overwritten.
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <typeparam name="TValue"></typeparam>
    public void Add<TValue>(string key, TValue value)
    {
        _cache[key] = value;
    }

    /// <summary>
    /// Remove the key from the request cache
    /// </summary>
    /// <param name="key"></param>
    public void Remove(string key)
    {
        if (_cache.ContainsKey(key))
        {
            _cache.Remove(key);
        }
    }

    /// <summary>
    /// Retrieve the value by key, if the key is not in the cache then the add func is called
    /// adding the value to cache and returning the added value.
    /// </summary>
    /// <param name="key"></param>
    /// <param name="add"></param>
    /// <typeparam name="TValue"></typeparam>
    /// <returns></returns>
    public TValue RetrieveOrAdd<TValue>(string key, Func<TValue> add)
    {
        if (_cache.ContainsKey(key))
        {
            return (TValue)_cache[key];
        }

        var value = add();

        _cache[key] = value;

        return value;
    }

    /// <summary>
    /// Retrieves the value by key. When the key does not exist the default value for the type is returned.
    /// </summary>
    /// <param name="key"></param>
    /// <typeparam name="TValue"></typeparam>
    /// <returns></returns>
    public TValue Retrieve<TValue>(string key)
    {
        if (_cache.ContainsKey(key))
        {
            return (TValue)_cache[key];
        }

        return default(TValue);
    }
}

ASP.Net Core के DI framework का उपयोग करके हम इसे Scoped के रूप में wire up करेंगे।

services.AddScoped<IRequestCache, RequestCache>();

Usage

public class UserService
{
    private readonly IRequestCache _cache;
    private readonly IUserRepository _userRepository;

    public UserService(IRequestCache cache, IUserRepository userRepository)
    {
        _cache = cache;
        _userRepository = userRepository;
    }

    public User RetrieveUserById(int userId)
    {
        var buildCacheKey = UserService.BuildCacheKey(userId);

        return _cache.RetrieveOrAdd(BuildCacheKey, () => { return _userRepository.RetrieveUserBy(userId); });
    }

    public void Delete(int userId)
    {
        var buildCacheKey = UserService.BuildCacheKey(userId);

        _userRepository.Delete(userId);
        _cache.Remove(BuildCacheKey(userId));
    }

    private static string BuildCacheKey(int userId)
    {
        return $"user_{userId}";
    }
}

बस यही! Request Caching अब किसी भी जगह injectable है जहां आपको इसकी जरूरत है।

Git Repository पर जाएं और बेझिझक code को आजमाएं।

लेखक: चक कॉनवे सॉफ्टवेयर इंजीनियरिंग और जेनेरेटिव AI में विशेषज्ञता रखते हैं। उनसे सोशल मीडिया पर जुड़ें: X (@chuckconway) या उन्हें YouTube पर देखें।

↑ शीर्ष पर वापस

आपको यह भी पसंद आ सकता है