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!

Agent.ai Challenge image

Congrats to the Agent.ai Challenge Winners πŸ†

The wait is over! We are excited to announce the winners of the Agent.ai Challenge.

From meal planners to fundraising automators to comprehensive stock analysts, our team of judges hung out with a lot of agents and had a lot to deliberate over. There were so many creative and innovative submissions, it is always so difficult to select our winners.

Read more β†’

Top comments (1)

Collapse
 
iamlobito profile image
Lobito β€’

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more