Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 56

Azure Cache for Redis: Basic .NET Operations

Recommended resources

Introduction

In our last lesson, you successfully provisioned your first Azure Cache for Redis instance and retrieved its connection string. We now have a high-performance cache waiting to be used. The next logical step, and the focus of this lesson, is to connect your .NET application to this cache and begin interacting with it.

Today, you will learn how to perform the three fundamental cache operationsโ€”setting, getting, and deleting dataโ€”programmatically using the .NET SDK. We'll be working with StackExchange.Redis, the most widely-used and high-performance Redis client for .NET. Mastering these operations is a core requirement for the AZ-204 exam and the foundation for building fast, scalable applications.


Connecting Your .NET Application to Redis

To communicate with a Redis instance from a .NET application, you'll use a client library. While there are a few options, StackExchange.Redis is the de facto standard, known for its performance and robustness.

The two most important concepts from this library you need to understand are:

  • ConnectionMultiplexer: This is the central object that manages the connection to your Redis instance. It is designed to be created once and reused throughout the lifetime of your application. Therefore, it should always be registered as a singleton in your dependency injection container. Creating a new ConnectionMultiplexer for each operation is a performance anti-pattern.
  • IDatabase: You get an IDatabase object from the ConnectionMultiplexer. This object is your primary interface for executing Redis commands like getting, setting, and deleting keys.

The following video provides an excellent, practical walkthrough of integrating Redis into a .NET API. We will use it to guide us through the implementation steps.

How Azure Redis Cache can make your .NET 7 API Super Fast!

The video "How Azure Redis Cache can make your .NET 7 API Super Fast!" by Israel Quiroz demonstrates the entire process, from setting up the client to implementing the operations within a service classโ€”a pattern you'll be very familiar with.

First, watch these three segments to see how to set up the project: Install the package: This shows the StackExchange.Redis NuGet package you need. Define the interface: The author creates an IRedisCache interface with methods for Get, Set, and Remove. This is a great practice for creating a testable and maintainable cache abstraction layer. Configure DI: This crucial part shows how to register the ConnectionMultiplexer as a singleton and your new IRedisCache service in Program.cs. The connection string you obtained in the last lesson would be placed in your appsettings.json.


Performing Basic Cache Operations

With the connection configured, you can now implement the core operations. All data in Redis is stored as a key-value pair. The value is often a string, but it can be a serialized representation of any C# object (e.g., a JSON string).

Let's look at the C# implementation for the Set, Get, and Delete operations. The video segment below implements the interface we just saw. As you watch, pay close attention to the StackExchange.Redis methods being used.

How Azure Redis Cache can make your .NET 7 API Super Fast!

Let's return to the same video to see the implementation details for each operation.

Watch the segment from implementing the class. Focus on how the following core StackExchange.Redis commands are used: Set: _db.StringSetAsync(key, serializedValue, expiryTime) is used to store data. Notice the use of JSON serialization to store a complex object and the critical expiryTime parameter to set a Time-To-Live (TTL). Get: _db.StringGetAsync(key) is used to retrieve data. The code then checks if the result is null (a cache miss) and deserializes it if found (a cache hit). Delete: _db.KeyDeleteAsync(key) is used to remove an entry from the cache, a process often called cache invalidation.

To reinforce this, here is a clear code example of a service implementing these operations, taken from the "How to Implement Cache-Aside Pattern" article. This code is very similar to what you saw in the video and cleanly demonstrates the three key asynchronous methods.

How to Implement Cache-Aside Pattern with Azure Cache for Redis ...

This article provides a concise C# implementation of a ProductService that interacts with Redis.

Focus on the ProductService class in the C# code block. In GetProductAsync, find the calls to _cache.StringGetAsync (get) and _cache.StringSetAsync (set). In UpdateProductAsync, find the call to _cache.KeyDeleteAsync (delete). This provides a static code view of the same concepts shown dynamically in the video.

The three core methods are:

  1. StringSetAsync(RedisKey key, RedisValue value, TimeSpan? expiry = null): This method sets a string value for a given key. You must first serialize your C# objects into a string (typically JSON). The optional expiry parameter is essential for ensuring that stale data is eventually removed from the cache.

  2. StringGetAsync(RedisKey key): This retrieves the value associated with a key. It returns RedisValue.Null if the key does not exist (a "cache miss"). If a value is found, you must deserialize it back into your C# object.

  3. KeyDeleteAsync(RedisKey key): This method deletes a key-value pair from the cache. This is crucial for cache invalidation, which you perform when the original data source has been updated, ensuring that the next read will fetch the fresh data.


Applying the Operations: A Practical Example

These basic operations are the building blocks for caching patterns. The most common pattern is cache-aside, where your application logic explicitly handles the cache.

The flow is simple:

  1. Your application needs data. It first asks the cache (Get operation).
  2. If the cache has the data (a cache hit), it's returned immediately.
  3. If the cache doesn't have the data (a cache miss), the application fetches it from the primary database.
  4. The application then stores the data in the cache (Set operation) so that the next request will be a cache hit.
  5. When data is updated or deleted in the database, the corresponding entry in the cache is removed (Delete operation).

The following video segments show this pattern in action within a .NET API controller, using the IRedisCache service we've been building.

How Azure Redis Cache can make your .NET 7 API Super Fast!

Now, let's see how the cache service is used within an API controller to improve performance.

Watch the final segments of the video: Using the cache: Observe how the GetTeams endpoint is modified. It first calls GetCacheData. If that returns null, it fetches from the repository and then calls SetCacheData. This is a perfect demonstration of the cache-aside pattern for reads. Get and Set Demo: The author runs the API and shows that the first request goes to the database, while the second request hits the cache. Remove Demo: Finally, the RemoveData method is called to invalidate the cache, demonstrating the delete operation.

This practical example solidifies how the set, get, and delete operations work together in a real-world scenario to provide a tangible performance benefit.


Conclusion

In this lesson, you've bridged the gap between having a provisioned Redis instance and actively using it in your .NET code. You now have the practical skills to perform the fundamental operations that underpin all caching strategies.

Here are the key takeaways:

  • The StackExchange.Redis library is the standard for connecting .NET applications to Redis.
  • The ConnectionMultiplexer should be a singleton instance, shared across your application.
  • The three core operations are StringSetAsync (to set data with an expiration), StringGetAsync (to retrieve data), and KeyDeleteAsync (to invalidate data).
  • These operations are the building blocks for common caching patterns like cache-aside, where the application logic manages reading from and writing to the cache.

In our next lesson, we will build directly on this foundation. We will take a deeper dive into the cache-aside pattern, formalizing its implementation and exploring best practices and considerations for using it effectively in your solutions.