Azure Cache for Redis CRUD (Create, Read, Update, Delete) operations:
Python:
Azure Cache for Redis facilitates standard CRUD (Create, Read, Update, Delete) operations on data stored in memory. These operations are performed using Redis commands, which can be executed through various client libraries or directly via the Redis Console in the Azure portal.
1. Create (Set):
To create or add data to the cache, the SET command is typically used. This command associates a key with a value.
Code:
SET mykey "myvalue"
2. Read (Get):
To retrieve data from the cache, the GET command is used, specifying the key of the desired value.
Code:
GET mykey
3. Update (Set/Incr/HSet):
Updating data can involve overwriting an existing value with SET, incrementing a numerical value with INCR (for integers), or modifying specific fields within a hash with HSET.
Code:
SET mykey "newvalue" // Overwrite
INCR counterkey // Increment a numerical value
HSET user:1 name "Alice" age 30 // Update fields in a hash
4. Delete (Del):
To remove data from the cache, the DEL command is used, specifying one or more keys to be deleted.
Code:
DEL mykey
DEL key1 key2 key3
Data Types:
Redis supports various data types beyond simple strings, including hashes, lists, sets, and sorted sets, each with specific commands for performing CRUD-like operations on their respective structures. For example, LPUSH and RPUSH for lists, SADD for sets, and ZADD for sorted sets are used to add elements, while LPOP, RPOP, SREM, and ZREM are used to remove elements.
Python:
"""
pip install redis
py azure_redis_cache.py
Azure Redis Cache - Get and Set Methods
Simple example demonstrating connection and basic operations with Azure Redis Cache
"""
import redis
import json
from typing import Optional, Any
# Redis connection string
REDIS_CONNECTION_STRING = "myazurerediscache.redis.cache.windows.net:6380,password=password=,ssl=True,abortConnect=False"
class AzureRedisCache:
"""Azure Redis Cache client wrapper"""
def __init__(self, connection_string: str):
"""
Initialize Redis connection
Args:
connection_string: Redis connection string
"""
# Parse connection string
params = {}
for param in connection_string.split(','):
if '=' in param:
key, value = param.split('=', 1)
params[key.strip()] = value.strip()
else:
# First part is host:port
host_port = param.split(':')
params['host'] = host_port[0]
params['port'] = int(host_port[1])
# Create Redis client
self.client = redis.StrictRedis(
host=params.get('host'),
port=params.get('port', 6380),
password=params.get('password'),
ssl=params.get('ssl', 'True').lower() == 'true',
decode_responses=True
)
print(f"✓ Connected to Redis: {params.get('host')}")
def set_value(self, key: str, value: Any, expiration: Optional[int] = None) -> bool:
"""
Set a value in Redis cache
Args:
key: Cache key
value: Value to store (will be JSON serialized if not a string)
expiration: Optional expiration time in seconds
Returns:
True if successful, False otherwise
"""
try:
# Convert value to string if it's not already
if not isinstance(value, str):
value = json.dumps(value)
if expiration:
result = self.client.setex(key, expiration, value)
else:
result = self.client.set(key, value)
print(f"✓ Set key '{key}' = '{value}'" + (f" (expires in {expiration}s)" if expiration else ""))
return bool(result)
except Exception as e:
print(f"✗ Error setting key '{key}': {str(e)}")
return False
def get_value(self, key: str) -> Optional[Any]:
"""
Get a value from Redis cache
Args:
key: Cache key
Returns:
Value if found, None otherwise
"""
try:
value = self.client.get(key)
if value is None:
print(f"✗ Key '{key}' not found")
return None
# Try to parse as JSON, otherwise return as string
try:
value = json.loads(value)
except (json.JSONDecodeError, TypeError):
pass
print(f"✓ Get key '{key}' = '{value}'")
return value
except Exception as e:
print(f"✗ Error getting key '{key}': {str(e)}")
return None
def delete_key(self, key: str) -> bool:
"""
Delete a key from Redis cache
Args:
key: Cache key to delete
Returns:
True if key was deleted, False otherwise
"""
try:
result = self.client.delete(key)
if result:
print(f"✓ Deleted key '{key}'")
else:
print(f"✗ Key '{key}' not found")
return bool(result)
except Exception as e:
print(f"✗ Error deleting key '{key}': {str(e)}")
return False
def key_exists(self, key: str) -> bool:
"""
Check if a key exists in Redis cache
Args:
key: Cache key
Returns:
True if key exists, False otherwise
"""
try:
exists = self.client.exists(key)
print(f"✓ Key '{key}' exists: {bool(exists)}")
return bool(exists)
except Exception as e:
print(f"✗ Error checking key '{key}': {str(e)}")
return False
def ping(self) -> bool:
"""
Test connection to Redis
Returns:
True if connection is successful, False otherwise
"""
try:
result = self.client.ping()
print(f"✓ Ping successful: {result}")
return result
except Exception as e:
print(f"✗ Ping failed: {str(e)}")
return False
def main():
"""Main function demonstrating Redis operations"""
print("=" * 60)
print("Azure Redis Cache - Get and Set Demo")
print("=" * 60)
print()
# Initialize Redis client
cache = AzureRedisCache(REDIS_CONNECTION_STRING)
# Test connection
print("\n--- Testing Connection ---")
cache.ping()
# Example 1: Set and get a simple string
print("\n--- Example 1: Simple String ---")
cache.set_value("greeting", "Hello, Azure Redis!")
cache.get_value("greeting")
# Example 2: Set and get a JSON object
print("\n--- Example 2: JSON Object ---")
user_data = {
"name": "John Doe",
"email": "john.doe@example.com",
"age": 30
}
cache.set_value("user:1001", user_data)
retrieved_user = cache.get_value("user:1001")
# Example 3: Set with expiration (10 seconds)
print("\n--- Example 3: Value with Expiration ---")
cache.set_value("temp_token", "abc123xyz", expiration=10)
cache.get_value("temp_token")
# Example 4: Check if key exists
print("\n--- Example 4: Check Key Existence ---")
cache.key_exists("greeting")
cache.key_exists("nonexistent_key")
# Example 5: Delete a key
print("\n--- Example 5: Delete Key ---")
cache.delete_key("greeting")
cache.get_value("greeting") # Should return None
print("\n" + "=" * 60)
print("Demo completed!")
print("=" * 60)
if __name__ == "__main__":
main()
Output:
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StackExchange.Redis;
using Newtonsoft.Json;
namespace AzureRedisCacheDemo
{
/// <summary>
/// Azure Redis Cache client wrapper
/// </summary>
public class AzureRedisCache : IDisposable
{
private readonly ConnectionMultiplexer _connection;
private readonly IDatabase _db;
private readonly string _host;
/// <summary>
/// Initialize Redis connection
/// </summary>
/// <param name="connectionString">Redis connection string</param>
public AzureRedisCache(string connectionString)
{
// Parse connection string
var parameters = ParseConnectionString(connectionString);
_host = parameters["host"];
// Create configuration options
var configOptions = new ConfigurationOptions
{
EndPoints = { $"{parameters["host"]}:{parameters["port"]}" },
Password = parameters["password"],
Ssl = parameters.GetValueOrDefault("ssl", "true").Equals("true", StringComparison.OrdinalIgnoreCase),
AbortOnConnectFail = parameters.GetValueOrDefault("abortConnect", "false").Equals("true", StringComparison.OrdinalIgnoreCase)
};
// Create Redis connection
_connection = ConnectionMultiplexer.Connect(configOptions);
_db = _connection.GetDatabase();
Console.WriteLine($"✓ Connected to Redis: {_host}");
}
/// <summary>
/// Parse connection string into parameters
/// </summary>
private Dictionary<string, string> ParseConnectionString(string connectionString)
{
var parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var parts = connectionString.Split(',');
foreach (var part in parts)
{
var trimmedPart = part.Trim();
if (trimmedPart.Contains('='))
{
var keyValue = trimmedPart.Split(new[] { '=' }, 2);
parameters[keyValue[0].Trim()] = keyValue[1].Trim();
}
else
{
// First part is host:port
var hostPort = trimmedPart.Split(':');
parameters["host"] = hostPort[0];
parameters["port"] = hostPort.Length > 1 ? hostPort[1] : "6380";
}
}
return parameters;
}
/// <summary>
/// Set a value in Redis cache
/// </summary>
/// <param name="key">Cache key</param>
/// <param name="value">Value to store</param>
/// <param name="expiration">Optional expiration time in seconds</param>
/// <returns>True if successful, false otherwise</returns>
public bool SetValue(string key, object value, int? expiration = null)
{
try
{
// Convert value to string
string stringValue = value is string str ? str : JsonConvert.SerializeObject(value);
// Set with or without expiration
bool result;
if (expiration.HasValue)
{
result = _db.StringSet(key, stringValue, TimeSpan.FromSeconds(expiration.Value));
Console.WriteLine($"✓ Set key '{key}' = '{stringValue}' (expires in {expiration}s)");
}
else
{
result = _db.StringSet(key, stringValue);
Console.WriteLine($"✓ Set key '{key}' = '{stringValue}'");
}
return result;
}
catch (Exception ex)
{
Console.WriteLine($"✗ Error setting key '{key}': {ex.Message}");
return false;
}
}
/// <summary>
/// Get a value from Redis cache
/// </summary>
/// <param name="key">Cache key</param>
/// <returns>Value if found, null otherwise</returns>
public string GetValue(string key)
{
try
{
var value = _db.StringGet(key);
if (value.IsNullOrEmpty)
{
Console.WriteLine($"✗ Key '{key}' not found");
return null;
}
string stringValue = value.ToString();
Console.WriteLine($"✓ Get key '{key}' = '{stringValue}'");
return stringValue;
}
catch (Exception ex)
{
Console.WriteLine($"✗ Error getting key '{key}': {ex.Message}");
return null;
}
}
/// <summary>
/// Get a value and deserialize to type T
/// </summary>
public T GetValue<T>(string key)
{
try
{
var value = GetValue(key);
if (value == null) return default(T);
// Try to deserialize as JSON
try
{
return JsonConvert.DeserializeObject<T>(value);
}
catch
{
// If deserialization fails, try to cast directly
return (T)Convert.ChangeType(value, typeof(T));
}
}
catch (Exception ex)
{
Console.WriteLine($"✗ Error deserializing key '{key}': {ex.Message}");
return default(T);
}
}
/// <summary>
/// Delete a key from Redis cache
/// </summary>
/// <param name="key">Cache key to delete</param>
/// <returns>True if key was deleted, false otherwise</returns>
public bool DeleteKey(string key)
{
try
{
bool result = _db.KeyDelete(key);
if (result)
{
Console.WriteLine($"✓ Deleted key '{key}'");
}
else
{
Console.WriteLine($"✗ Key '{key}' not found");
}
return result;
}
catch (Exception ex)
{
Console.WriteLine($"✗ Error deleting key '{key}': {ex.Message}");
return false;
}
}
/// <summary>
/// Check if a key exists in Redis cache
/// </summary>
/// <param name="key">Cache key</param>
/// <returns>True if key exists, false otherwise</returns>
public bool KeyExists(string key)
{
try
{
bool exists = _db.KeyExists(key);
Console.WriteLine($"✓ Key '{key}' exists: {exists}");
return exists;
}
catch (Exception ex)
{
Console.WriteLine($"✗ Error checking key '{key}': {ex.Message}");
return false;
}
}
/// <summary>
/// Test connection to Redis
/// </summary>
/// <returns>True if connection is successful, false otherwise</returns>
public bool Ping()
{
try
{
var endPoint = _connection.GetEndPoints().First();
var server = _connection.GetServer(endPoint);
var latency = server.Ping();
Console.WriteLine($"✓ Ping successful: {latency.TotalMilliseconds}ms");
return true;
}
catch (Exception ex)
{
Console.WriteLine($"✗ Ping failed: {ex.Message}");
return false;
}
}
/// <summary>
/// Dispose connection
/// </summary>
public void Dispose()
{
_connection?.Dispose();
}
}
/// <summary>
/// User data model for demonstration
/// </summary>
public class UserData
{
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public int Age { get; set; }
}
class Program
{
// Redis connection string
const string REDIS_CONNECTION_STRING = "myazurerediscache.redis.cache.windows.net:6380,password=password=,ssl=True,abortConnect=False";
static void Main(string[] args)
{
Console.WriteLine("============================================================");
Console.WriteLine("Azure Redis Cache - Get and Set Demo (C#)");
Console.WriteLine("============================================================");
Console.WriteLine();
using (var cache = new AzureRedisCache(REDIS_CONNECTION_STRING))
{
// Test connection
Console.WriteLine("\n--- Testing Connection ---");
cache.Ping();
// Example 1: Set and get a simple string
Console.WriteLine("\n--- Example 1: Simple String ---");
cache.SetValue("greeting", "Hello, Azure Redis!");
cache.GetValue("greeting");
// Example 2: Set and get a JSON object
Console.WriteLine("\n--- Example 2: JSON Object ---");
var userData = new UserData
{
Name = "John Doe",
Email = "john.doe@example.com",
Age = 30
};
cache.SetValue("user:1001", userData);
var retrievedUser = cache.GetValue<UserData>("user:1001");
if (retrievedUser != null)
{
Console.WriteLine($" Retrieved: {retrievedUser.Name}, {retrievedUser.Email}, Age: {retrievedUser.Age}");
}
// Example 3: Set with expiration (10 seconds)
Console.WriteLine("\n--- Example 3: Value with Expiration ---");
cache.SetValue("temp_token", "abc123xyz", expiration: 10);
cache.GetValue("temp_token");
// Example 4: Check if key exists
Console.WriteLine("\n--- Example 4: Check Key Existence ---");
cache.KeyExists("greeting");
cache.KeyExists("nonexistent_key");
// Example 5: Delete a key
Console.WriteLine("\n--- Example 5: Delete Key ---");
cache.DeleteKey("greeting");
cache.GetValue("greeting"); // Should return null
Console.WriteLine("\n============================================================");
Console.WriteLine("Demo completed!");
Console.WriteLine("============================================================");
}
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Output:
No comments:
Post a Comment