Cookie Consent by Free Privacy Policy Generator ASP.NET Core Cache - An Overview - NCache

ASP.NET Core Cache - An Overview

Modern web applications require fast performance and scalability. As applications grow, frequent database queries can slow things down, leading to performance bottlenecks and reduced responsiveness.

ASP.NET Core is a powerful framework for building scalable web applications, but it performs well when combined with a distributed caching solution like NCache. Caching frequently accessed data reduces database load, increases the response time, and improves scalability.

Let's discuss the benefits of distributed caching, its real-world use cases, and how to integrate NCache with ASP.NET Core applications.

 

Understanding Distributed Caching

Distributed caching stores frequently used data across multiple servers, making a scalable and reliable in-memory data store. This helps reduce latency, minimizes database queries, and improves application responsiveness.

  • Faster Performance - Delivers cached data in-memory, greatly reducing response times.
  • Seamless Scalability - Expands horizontally by adding cache nodes as demand increases.
  • High Availability - Ensures reliability with data replication, preventing downtime if a server fails.
  • Efficient Resource Utilization - Reduces database load by caching frequent read operations.
 

Setting Up NCache for ASP.NET Core

Follow these steps to install and configure NCache for your ASP.NET Core application.

Step 1: Install NCache

Installing NCache Server

Install NCache Server on two servers from the official website.

Installing NCache Client SDK

To connect an ASP.NET Core application to the cache server, install the NCache Client SDK using NuGet:

Install-Package Alachisoft.NCache.SDK

Ensure your network and firewall settings allow communication between your application and the cache server.

Step 2: Creating a Clustered Cache

A clustered cache improves scalability and ensures high availability by distributing cached data across multiple servers.

  1. Verify Network Connectivity - Ensure cache nodes can communicate over the designated network ports.
  2. Configure NCache - Use NCache Management Center or PowerShell to create a clustered cache instance.
  3. Add Cache Nodes - Add multiple servers to improve performance and reliability.
  4. Monitor Cache Health - Track synchronization and node availability through NCache's monitoring tools.

Step 3: Installing & Configuring the .NET Client

After setting up NCache, configure your ASP.NET Core application to connect to the cache.

Program.cs (Modify)

using Alachisoft.NCache.Client;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<ICache>(_ => CacheManager.GetCache("demoCache"));

var app = builder.Build();
app.Run();
 

Using NCache in ASP.NET Core

1. Retrieving Data from the Cache

This method retrieves multiple products from the cache using their product IDs in bulk, reducing the number of calls to the cache server.

public Dictionary<string, Product> RetrieveProducts(List<int> productIds)
{
    List<string> cacheKeys = productIds.Select(id => $"Product:{id}").ToList();
    Dictionary<string, Product> cachedProducts = _cache.GetBulk<Product>(cacheKeys);
    return cachedProducts;
}

2. Adding Data to the Cache

This method attempts to fetch a product from the cache; if it does not exist, it fetches it from the database and adds it to the cache with an expiration time.

public Product GetProduct(int productId)
{
    string cacheKey = $"Product:{productId}";
    Product product = _cache.Get<Product>(cacheKey);

    if (product == null)
    {
        product = FetchProductFromDB(productId);
        var cacheItem = new CacheItem(product)
        {
            Expiration = new Expiration(ExpirationType.Absolute, TimeSpan.FromMinutes(10))
        };
        _cache.Add(cacheKey, cacheItem);
    }
    
    return product;
}

3. Updating/Inserting Data in the Cache

This method updates the product in the database first and then inserts or updates the cached product with a specified expiration.

public void UpdateProduct(int productId, Product updatedProduct)
{
    // Update the database first
    UpdateProductInDB(productId, updatedProduct);
    
    // Update the cache after successful database update
    string cacheKey = $"Product:{productId}";
    var cacheItem = new CacheItem(updatedProduct)
    {
        Expiration = new Expiration(ExpirationType.Absolute, TimeSpan.FromMinutes(10))
    };
    _cache.Insert(cacheKey, cacheItem);
}

4. Removing Cached Data

This method removes multiple entries from the cache at once using their cache keys.

public void RemoveData(List<string> keys)
{
    _cache.RemoveBulk(keys);
}
 

Advanced Caching Features

NCache offers additional enterprise-level caching features to enhance performance:

 

Get Started with NCache Today!

Optimize your ASP.NET Core applications with NCache! Reduce database load, enhance performance, and scale effortlessly.

© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.