Tutorial: Using Azure Cache for Redis with TypeScript This tutorial guides you through setting up and using Azure Cache for Redis in a TypeScript application, implementing the cache-aside pattern. We'll use the ioredis library for Redis connectivity and demonstrate basic caching operations. Prerequisites
An active Azure subscription Node.js (v16 or later) and npm installed An Azure Cache for Redis instance (Basic, Standard, Premium, or Enterprise tier) TypeScript installed (npm install -g typescript)
Step 1: Create an Azure Cache for Redis Instance
Log in to the Azure Portal. Create a new Azure Cache for Redis resource: Choose a subscription and resource group. Select a tier (e.g., Basic for development). Provide a unique cache name and region. Configure networking (use public access for simplicity in this tutorial).
Once created, note the Host Name (e.g., yourcache.redis.cache.windows.net), Port (usually 6380 for SSL), and Access Key from the "Access keys" section.
Step 2: Set Up Your TypeScript Project
Create a new directory for your project and initialize it:mkdir azure-redis-demo cd azure-redis-demo npm init -y
Install required dependencies:npm install ioredis typescript ts-node @types/node
Initialize TypeScript configuration:npx tsc --init
Update tsconfig.json to include:{ "compilerOptions": { "target": "ES2020", "module": "commonjs", "strict": true, "esModuleInterop": true, "outDir": "./dist" } }
Step 3: Implement the Cache-Aside Pattern The cache-aside pattern involves checking the cache first for data. If the data is not found (cache miss), fetch it from the primary data source (e.g., a database) and store it in the cache for future requests. Below is a sample TypeScript code that demonstrates connecting to Azure Cache for Redis, performing basic cache operations, and implementing the cache-aside pattern.
import Redis from 'ioredis';
// Configuration for Azure Cache for Redisconst redisConfig = { host: 'yourcache.redis.cache.windows.net', // Replace with your cache host name port: 6380, // Default SSL port password: 'your-access-key', // Replace with your primary access key tls: {}, // Enable SSL for Azure Cache for Redis};
// Initialize Redis clientconst redis = new Redis(redisConfig);
// Simulated database fetch (replace with actual database logic)async function fetchFromDatabase(key: string): Promise { console.log(Fetching ${key} from database...); // Simulate database delay await new Promise(resolve => setTimeout(resolve, 1000)); return Data for ${key};}
// Cache-aside pattern implementationasync function getCachedData(key: string): Promise { try { // Check cache first const cachedData = await redis.get(key); if (cachedData) { console.log(Cache hit for key: ${key}); return cachedData; }
// Cache miss: fetch from database
console.log(Cache miss for key: ${key});
const data = await fetchFromDatabase(key);
// Store in cache with 60-second expiration
await redis.set(key, data, 'EX', 60);
console.log(Stored ${key} in cache);
return data;
} catch (error) { console.error('Error accessing Redis:', error); // Fallback to database if Redis fails return fetchFromDatabase(key); }}
// Example usageasync function main() { try { // Test cache-aside pattern const key = 'user:123';
// First call: should hit database
console.log('First call:');
const data1 = await getCachedData(key);
console.log(Result: ${data1}\n);
// Second call: should hit cache
console.log('Second call:');
const data2 = await getCachedData(key);
console.log(Result: ${data2}\n);
// Clean up: close Redis connection await redis.quit();
} catch (error) { console.error('Error in main:', error); }} // Run the examplemain();