Skip to content

Lightweight library to cache API responses in NET Core using memory cache or distributed cache with Redis

Notifications You must be signed in to change notification settings

BetimShala/ResponseCache

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ResponseCache

ResponseCache

NuGet

What is ResponseCache?

ResponseCache is a lightweight library that is used to cache API responses by simply putting ResponseCache attribute to the endpoint you want to cache.

Setup

NuGet install:

Install-Package ResponseCache

Memory Cache configuration

services.AddMemoryCache();
services.AddInMemoryResponseCache();

Redis Cache configuration

First we bind cache settings with configuration values from appsettings.json then we add the service

var cacheSettings = new CacheSettings();
Configuration.GetSection(nameof(CacheSettings)).Bind(cacheSettings);
services.AddSingleton(cacheSettings);

services.AddSingleton<IConnectionMultiplexer>(_ => ConnectionMultiplexer.Connect(cacheSettings.ConnectionString));
services.AddDistributedRedisCache(options => options.Configuration = cacheSettings.ConnectionString);

services.AddDistributedResponseCache();

Add this to appsettings.json

  "CacheSettings": {
    "ConnectionString": "localhost:6379"
  },

Usage

[ResponseCache(TTL)] attribute where TTL is an integer representing cache living time in seconds.

Example

e.g. Cache response list of products for 1 minute

[ApiController]
[Route("[controller]")]
public class ProductsController : ControllerBase
{
    private readonly DbContext _context;

    public ProductsController(DbContext context)
    {
        _context = context;
    }

    [HttpGet]
    [ResponseCache(60)]
    public async Task<IActionResult> List()
    {
        return Ok(await _context.Products.ToListAsync());
    }
}     

About

Lightweight library to cache API responses in NET Core using memory cache or distributed cache with Redis

Topics

Resources

Stars

Watchers

Forks

Languages