Integrate caching and content delivery within solutions
Best practices Caching
Develop for Azure Cache for Redis
After completing this module, you’ll be able to:
- Explain the key scenarios Azure Cache for Redis covers and its service tiers.
- Identify the key parameters for creating an Azure Cache for Redis instance and interact with the cache.
- Connect an app to Azure Cache for Redis by using .NET Core.
Key scenarios
- Data cache: cache aside
- Content cache: header/footer/banner
- Session store: shopping carts
- Job and message queuing
- Distributed transactions: Applications sometimes require a series of commands against a backend data-store to execute as a single atomic operation. All commands must succeed, or all must be rolled back to the initial state.
Accessing the Redis instance
Command | Description | ||
---|---|---|---|
|
Ping the server. Returns “PONG”. | ||
|
Sets a key/value in the cache. Returns “OK” on success. | ||
|
Gets a value from the cache. | ||
|
Returns ‘1’ if the key exists in the cache, ‘0’ if it doesn’t. | ||
|
Returns the type associated to the value for the given key. | ||
|
Increment the given value associated with key by ‘1’. The value must be an integer or double value. This returns the new value. | ||
|
Increment the given value associated with key by the specified amount. The value must be an integer or double value. This returns the new value. | ||
|
Deletes the value associated with the key. | ||
|
Delete all keys and values in the database. |
1
2
3
# https://medium.com/@therealjordanlee/connecting-to-azure-cache-redis-with-redis-cli-and-stunnel-6e5c5479bc2c
sudo apt install -y redis-tools stunnel4
Exercise: Connect an app to Azure Cache for Redis by using .NET Core
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// dotnet new console -o Rediscache
// Program.cs
using System;
using StackExchange.Redis;
using System.Threading.Tasks;
namespace Rediscache
{
class Program
{
static string connectionString = "sfan-redis.redis.cache.windows.net:6380,password=xxx,ssl=True,abortConnect=False";
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
using(var cache = ConnectionMultiplexer.Connect(connectionString))
{
var db = cache.GetDatabase();
var result = await db.ExecuteAsync("ping");
Console.WriteLine($"{result.Type} {result}");
bool setValue = await db.StringSetAsync("key:test", "200");
var getValue = await db.StringGetAsync("key:test");
Console.WriteLine($"GET: {value}");
}
}
}
}