redis-on-azure-workshop

Data in Azure Cache for Redis

Learning Objective

Use Azure Cache for Redis to store frequently accessed data. Learn how to use ServiceStack.Redis to create transactions and manage data expiration.

Prerequisites

Create a transaction in Azure Cache for Redis

  1. Create a new .NET Core application, name it redis-data-dotnet.

     dotnet new console --name redis-data-dotnet --use-program-main
     cd redis-data-dotnet
     code .
    
  2. We need to add the ServiceStack.Redis NuGet package. This will enable us to connect to the Azure Cache for Redis, and issue commands in C#.

     dotnet add package ServiceStack.Redis
    
  3. Build and run the application to make sure it all compiles. It should output “Hello World!”

     dotnet run
    
  4. ServiceStack.Redis has its own connection string format: “[password]@[hostname]:[sslport]?ssl=true”. Use the az redis list-keys command to retrieve the access keys and output a correctly formatted connection string.

     REDIS_NAME=<redis-name>
     REDIS_KEY=$(az redis list-keys \
                 --name "$REDIS_NAME" \
                 --resource-group <resource-group> \
                 --query primaryKey \
                 --output tsv)
    
     echo "$REDIS_KEY"@"$REDIS_NAME".redis.cache.windows.net:6380?ssl=true
    
  5. Open Program.cs add create the following field in the Program class and paste in your connection string as the value.

     static string redisConnectionString = "<connection string>";
    

    If you recreated your Redis instance, this won’t be the same connection string from Lab 1.

  6. Add the following using statement to the top of the Program.cs file.

     using ServiceStack.Redis;
    
  7. In the Main method, declare a variable to store the result of the transaction.

     bool transactionResult = false;
    
  8. Using the redisConnectionString variable, create a new instance of the RedisClient class. This class will be used to interact with the Azure Cache for Redis instance.

     using RedisClient redisClient = new RedisClient(redisConnectionString);
    
  9. Create a new instance of the Transaction class. This class will be used to create, manage, and commit a transaction.

     using var transaction = redisClient.CreateTransaction();
    
  10. Add multiple operations to the transaction.

     transaction.QueueCommand(c => c.Set("MyKey1", "MyValue1"));
     transaction.QueueCommand(c => c.Set("MyKey2", "MyValue2"));
    
  11. Commit the transaction and store the result in the transactionResult variable.

     transactionResult = transaction.Commit();
    
  12. If the transaction was committed successfully, output a message to the console.

     if (transactionResult)
     {
         Console.WriteLine("Transaction committed");
     }
     else
     {
         Console.WriteLine("Transaction failed to commit");
     }
    
  13. Run the application, and verify that the console says Transaction committed.

     dotnet run
    
  14. Let’s verify the data we added is in our Azure Cache for Redis instance. In the Azure portal, navigate to your Azure Cache for Redis instance.

  15. In the Overview pane, select Console. This will open a Redis Console, which enables you to enter low-level Redis commands.

    Redis Console Menu

  16. Run the command get MyKey1. Verify that the value returned is “MyValue1”.

  17. Run the command get MyKey2. Verify that the value returned is “MyValue2”.

    Redis Console Transaction Result

Implement data expiration

  1. In the last exercise, we left off with the following code in Program.cs.

     bool transactionResult = false;
    
     using RedisClient redisClient = new RedisClient(redisConnectionString);
     using var transaction = redisClient.CreateTransaction();
        
     transaction.QueueCommand(c => c.Set("MyKey1", "MyValue1"));
     transaction.QueueCommand(c => c.Set("MyKey2", "MyValue2"));
    
     transactionResult = transaction.Commit();
    
     if (transactionResult)
     {
         Console.WriteLine("Transaction committed");
     }
     else
     {
         Console.WriteLine("Transaction failed to commit");
     }
    
  2. Let’s add an expiration of 15 seconds to both “MyKey1” and “MyKey2”. Add the following code before you commit the transaction:

     transaction.QueueCommand(c => ((RedisNativeClient)c).Expire("MyKey1", 15));
     transaction.QueueCommand(c => ((RedisNativeClient)c).Expire("MyKey2", 15));
    
  3. Now that we added the code to expire our data, let’s run the program and check that the data is removed from Azure Cache for Redis.

     dotnet run
    
  4. Switch back to the Azure Cache for Redis console in the Azure portal.

  5. Run the command get MyKey1. Verify that the value returned is “MyValue1”.

  6. After 15 seconds, run the command again. You should see that the data is no longer there.

    Redis Console Data Expiration

Cache-aside pattern

When building an application, you want to provide a great user experience, and a part of that is quick data retrieval. Retrieving data from a database is typically a slow process, and if this data is read often, this could provide a poor user experience. The cache-aside pattern describes how you can implement a cache in conjunction with a database, to return the most commonly accessed data as quickly as possible.

Why not have a go at implementing cache-aside? You can read more about the pattern here.

Additional Resources

  1. Work with mutable and partial data in Azure Cache for Redis

Next Lab