Memcached Distributed cache in ASP.NET Core

Memcached Distributed cache in ASPNET

Today in this article, we shall see how to Memcached Distributed cache in ASP.NET Core.

We will use EnyimMemcachedCore a C# NuGet library to add support for Memcached cache.

We shall cover basic aspects of MemCached as below,

What is Memcached?

A high-performance, distributed memory object caching system that is free and open source. It is generic in nature and intended for use in speeding up various applications, API, etc by reducing database load.

Memcached is a key-value store that stores short bits of arbitrary data (strings, objects) returned by database calls, API calls, or page rendering in memory.

Memcached is a simple yet powerful memory management system.

Advantages of MemCached

Faster than Disk – Memcached can respond in milliseconds or less. They can read data faster than disk-based databases because they store data in memory.

Simple to use – are simple to use and require little code to integrate into your application and ease of use by developers

Support multiple languages

Memcached supported languages include Java, Python, PHP, C, C++, C#, JavaScript, Node.js, Ruby, Go, and many others.

Multithreaded architecture

Support scaling up compute capacity due to Multithreaded architecture used by the framework

First, we will seed the data at startup I.e when our API gets hosted.

Data will be seeded once per configuration based on cache time Example 1 hour or 6 hours or a day.

All requests will be addressed using cached data giving the best experience to users using the API.

Getting started

Create .NET 3.1 or 6 API or MVC applications.

Please install the Memcached Nuget package as below,

EnyimMemcachedCore

Or

Install using PMC or CLI

PM> Install-Package EnyimMemcachedCore -Version 2.5.3

Let’s register the Memcached client service and enable the middleware in the API pipeline in the Startup class.

public void ConfigureServices(IServiceCollection services)
        {
          ....
          ....
            services.AddSingleton<IMemCachedStore>(x => 
            ActivatorUtilities.CreateInstance<MemCachedStore>(x));
            services.AddEnyimMemcached(setup => {
                setup.Servers.Add(new Server { Address = Configuration["CacheHost"], Port = 
                Int32.Parse(Configuration["Port"]) });
            });
           ....
           ....
        }

Update Configure method as below,

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
          ...
          ...
            app.UseEnyimMemcached();
          ...
        }

Below are my implementation for IMemCachedStore,

public interface IMemCachedStore
{
    Employee GetEmployee(Guid id);
}

Below is the implementation for class MemCachedStore.

public class MemCachedStore : IMemCachedStore
    {
        private List<Employee> _employees;
        private readonly IMemcachedClient _memCache;
        private const int _cacheSeconds = 3600;
        public MemCachedStore(IMemcachedClient cache)
        {
            this._memCache = cache;
            //connect to DB and initialize the data if any
            SeedData();
        }
        public Employee GetEmployee(Guid id)
        {
            Employee empRecord = this._memCache.Get<Employee>(id.ToString());
            if (empRecord == null)
            {
                ///Record not available in Cache hence get it from SQL DB or other 
                /// Once you get the record add this record into Cache
                if (this._memCache.Add(id.ToString(), empRecord, _cacheSeconds))
                {
                    
                }
            }
            return empRecord;
        }
    }

Above for demonstration purposes, we are Seeding the data as we are creating a singleton instance of IMemCachedStore, and later when a request arrives we do a lookup into MemcachedClient store and send the response. If data doesn’t exist then we lookup from the origin Database.

Dependency Injection IMemCachedStore

Let’s do dependency Injection for IMemCachedStore through constructor injection,

memcached c net core

Let’s execute the GET API for the know Id. We shall get a valid response from the cache.

enyim memcached example c

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *