2017年6月3日 星期六

[ASP.NET Core] In-Memory caching

 ASP.NET Core   In Memory Caching


Introduction


In-memory cache makes faster response and better user experience.
Let’s see how to use it in ASP.NET Core.


Environment


.NET Core 2.0.0 preview 1



Implement


Register service

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
     services.AddMemoryCache();
}


Inject IMemoryCache

Controller

private IMemoryCache _cache;
public CachedemoController(IMemoryCache memoryCache)
{
   this._cache = memoryCache;
}

I create a Dictionary to store my cache keys.

private IMemoryCache _cache;
private Dictionary<string, string> _cacheKeys = null;

public CachedemoController(IMemoryCache memoryCache)
{
     this._cache = memoryCache;

     this._cacheKeys = new Dictionary<string, string>();
     this._cacheKeys.Add("Datetime1", "Datetime1");
     this._cacheKeys.Add("Datetime2", "Datetime2");
}



Create or read in-memory cache

DateTime cacheDatetime1;
var key = this._cacheKeys["Datetime1"].ToString();
if (!this._cache.TryGetValue(key, out cacheDatetime1))
{
   //Get value
    cacheDatetime1 = DateTime.Now;

   // Set cache options
   var cacheEntryOptions = new MemoryCacheEntryOptions()
        .SetAbsoluteExpiration(TimeSpan.FromSeconds(5));
        //.SetSlidingExpiration(TimeSpan.FromSeconds(5));
   // Save data in cache.
   _cache.Set(key, cacheDatetime1, cacheEntryOptions);
}
                            
The difference between AbsoluteExpiration and SlidingExpiration is,
1.  In SlidingExpiration the expired time will reset to 5 sec again when the cache is hit and not expired.
2.  AbsoluteExpiration means the cache will be cleared definitely after 5 sec.

An easy way to achieve the above goal is using GetOrCreate method, see the following codes.

Using GetOrCreate method

var cacheDatetime2 = _cache.GetOrCreate(this._cacheKeys["Datetime2"], entry =>
{
      entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5);
      return DateTime.Now;
});


Just Get

var getDatetime = _cache.Get(this._cacheKeys["Datetime2"]);




Sample

I create a sample to show how these methods work.
The full sample codes is as following.

View

<h2>Non Cached Datetime : @ViewBag.CurrentDatetime</h2>
<h2>Cached Datetime1 : @ViewBag.CurrentDatetime1</h2>
<h2>Cached Datetime2 : @ViewBag.CurrentDatetime2</h2>


Controller

[Route("[action]")]
public IActionResult Now([FromQuery]string clear)
{
            var clearKey = this._cacheKeys.ToList().TakeWhile(x => x.Key.Equals(clear)).FirstOrDefault();
            if (!clearKey.Equals(default(KeyValuePair<string, string>)))
            { this._cache.Remove(clearKey.Value); }


            #region Traditional way
            DateTime cacheDatetime1;
            var key = this._cacheKeys["Datetime1"].ToString();
            if (!this._cache.TryGetValue(key, out cacheDatetime1))
            {
                //Get value
                cacheDatetime1 = DateTime.Now;

                // Set cache options
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                    // .SetSlidingExpiration(TimeSpan.FromSeconds(5));
                    .SetAbsoluteExpiration(TimeSpan.FromSeconds(5));

                // Save data in cache.
                _cache.Set(key, cacheDatetime1, cacheEntryOptions);
            }
            #endregion

            #region Use GetOrCreate method
            var cacheDatetime2 = _cache.GetOrCreate(this._cacheKeys["Datetime2"], entry =>
            {
                entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5);
                // entry.SlidingExpiration = TimeSpan.FromSeconds(5);
                return DateTime.Now;
            });
            #endregion

            ViewBag.CurrentDatetime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
            ViewBag.CurrentDatetime1 = cacheDatetime1.ToString("yyyy/MM/dd HH:mm:ss");
            ViewBag.CurrentDatetime2 = cacheDatetime2.ToString("yyyy/MM/dd HH:mm:ss");
            return View();
}


Demo




Reference





沒有留言:

張貼留言