DEV Community

VzlDev
VzlDev

Posted on

Redis Cache in .NET

Hello guys!

Today I'll demonstrate how to implement Redis Cache in a .NET project.

What is Redis Cache?

Redis is an open source (BSD licensed), in-memory data structure store that can be used as a database, cache, message broker, and streaming engine.

Why Redis?

  • All Redis data resides in memory, which enables low latency and high throughput data access. Unlike traditional databases, In-memory data stores don’t require a trip to disk, reducing engine latency to microseconds. Because of this, in-memory data stores can support an order of magnitude more operations and faster response times.

  • Easy to use.

  • High availability and scalability.

  • Open Source.

  • Flexible data structures.

Step 1

You need to configure your Redis server. For that you can download and run an image of Redis in a docker container.

Image description

Step 2

Once your Redis server is up and running you need to install the following nuget package

Microsoft.Extensions.Caching.StackExchangeRedis
Enter fullscreen mode Exit fullscreen mode

Step 3

On the ConnectionStrings section of the appsettings.json file, add the following entry

 "ConnectionStrings": {
    "Redis" : "localhost:6379"
  },
Enter fullscreen mode Exit fullscreen mode

Step 4

Then you need to configure your connection to the Redis server in the Program.cs file

builder.Services.AddStackExchangeRedisCache(redisOptions =>
{
    string connection = builder.Configuration.GetConnectionString("Redis");
    redisOptions.Configuration = connection;
});
Enter fullscreen mode Exit fullscreen mode

Step 5

On your controller, you'll need to inject IDistributedCachevia Dependency Injection.

        private readonly IDistributedCache? _cache;

        public TvShowsController(TvShowContext context, IDistributedCache cache)
        {
            _context = context;
            _cache = cache;
        }
Enter fullscreen mode Exit fullscreen mode

Step 6

Finally is time to store and retrieve values to and from your Redis Cache.

[HttpGet]
        public ActionResult<IEnumerable<TvShow>> GetTvShows()
        {
            string cachedData = _cache.GetString("cachedData");
            if (string.IsNullOrEmpty(cachedData))
            {
                var tvShows = _context.TvShows.ToList();
                string serializedObject = JsonConvert.SerializeObject(tvShows);
                _cache.SetString("cachedData", serializedObject, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) });
                return tvShows;
            }

            return JsonConvert.DeserializeObject<List<TvShow>>(cachedData);
        }
Enter fullscreen mode Exit fullscreen mode

I hope you liked it, stay tuned for more!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
iamlobito profile image
Lobito

More of this! Simple and objective tutorials. Super easy to understand.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay