Skip to main content
This article shows how to connect to and interact with Azure Cache for Redis from a .NET application using the StackExchange.Redis client. You’ll learn how to:
  • Create a connection to an Azure Cache for Redis instance
  • Obtain an IDatabase instance
  • Perform basic GET/SET operations with TTL (expiration)
  • Verify behavior with the Redis CLI
  • Review commonly used StackExchange.Redis methods for advanced scenarios
Useful links:
Do not hard-code credentials or connection strings in production code. Use Azure Managed Identity, environment variables, or Azure Key Vault to manage secrets securely.
Prerequisites
  • .NET SDK installed (3.1 / 5 / 6 / 7+)
  • An Azure Cache for Redis instance (obtain its host name, port, and access key)
  • Add the StackExchange.Redis package to your project:
Connecting to Redis and basic GET/SET The sample console application below demonstrates a complete flow:
  • Connect to an Azure Cache for Redis instance.
  • Obtain an IDatabase instance.
  • Store a value with a TTL (expiration).
  • Retrieve the value, wait for expiration, and confirm it is removed.
Basic Redis CLI interaction (example) You can verify the same key/value from the Redis CLI (connect using TLS/SSL if your Azure Cache for Redis instance requires it). Example session:
Redis methods overview StackExchange.Redis exposes many methods for working with cached data beyond simple GET/SET. The table below summarizes commonly used methods and their purposes so you can choose the right primitive for your scenario.
A presentation slide titled "Interacting With Azure Cache for Redis by Using .NET" showing a table of Redis methods (CreateBatch, CreateTransaction, KeyDelete, KeyExists, KeyExpire, KeyRename, KeyTimeToLive, KeyType) with brief descriptions.
Managing keys and cache lifecycle Use the methods above to control the lifecycle of cached items:
  • Set expirations for short-lived cached entries using StringSet with a TimeSpan or KeyExpire.
  • Check existence with KeyExists before conditional updates.
  • Remove stale entries with KeyDelete.
  • Rename keys atomically with KeyRename when reorganizing data.
  • Inspect KeyType to work appropriately with lists, sets, hashes, and sorted sets.
Choosing the right strategy (TTL, eviction policy, cache warming, and cache invalidation) helps ensure correctness and performance when using Redis as a distributed cache. Summary Using the StackExchange.Redis client, you can connect from .NET to Azure Cache for Redis, perform basic GET/SET operations, set expirations, and use advanced features such as batching and transactions to optimize throughput and concurrency. Follow best practices for secret management and connection handling in production. An alternative caching solution is also commonly used. Links and references

Watch Video