Comprehensive Redis operations demonstration with clean architecture, Microsoft Aspire orchestration, and modern .NET patterns
๐๏ธ Table of Contents
Redis Playground showcases 15 comprehensive Redis feature groups through a clean, modular ASP.NET Core API built with modern .NET patterns and cloud-native principles.
|
|
graph TB
A[๐ฏ AppHost<br/>Aspire Orchestration] --> B[๐ ApiService<br/>Main API]
A --> C[๐ฆ Redis Container<br/>Data Layer]
B --> D[๐ 15 Endpoint Modules]
B --> E[๐ง Service Defaults]
D --> F[๐ Models & DTOs]
D --> G[๐งช HTTP Test Collections]
style A fill:#e1f5fe
style B fill:#f3e5f5
style C fill:#ffebee
style D fill:#e8f5e8
๐ Detailed Project Structure
๐๏ธ RedisPlayground/
โโโ ๐ฏ RedisPlayground.AppHost/ # Aspire orchestration & service discovery
โโโ ๐ RedisPlayground.ApiService/ # Core API service
โ โโโ ๐ Endpoints/ # 15 feature-specific modules
โ โ โโโ 01-BasicCacheEndpoints.cs # IDistributedCache operations
โ โ โโโ 02-StringEndpoints.cs # String & counter operations
โ โ โโโ 03-HashEndpoints.cs # Hash/dictionary operations
โ โ โโโ 04-ListEndpoints.cs # Queue & stack operations
โ โ โโโ 05-SetEndpoints.cs # Set operations & membership
โ โ โโโ 06-SortedSetEndpoints.cs # Leaderboards & rankings
โ โ โโโ 07-PubSubEndpoints.cs # Real-time messaging
โ โ โโโ 08-StreamEndpoints.cs # Event streaming
โ โ โโโ 09-GeospatialEndpoints.cs # Location services
โ โ โโโ 11-JsonEndpoints.cs # JSON document operations
โ โ โโโ 12-BitfieldEndpoints.cs # Bit manipulation
โ โ โโโ 13-LockEndpoints.cs # Distributed locking
โ โ โโโ 14-AnalyticsEndpoints.cs # Bloom filters & analytics
โ โ โโโ 15-DeveloperToolsEndpoints.cs # Dev utilities & diagnostics
โ โโโ ๐ Models/ # Request/response DTOs
โ โโโ ๐ง Extensions/ # Endpoint registration
โ โโโ ๐งช HttpTests/ # Comprehensive test collections
โโโ โ๏ธ RedisPlayground.ServiceDefaults/ # Shared configuration & middleware
โโโ ๐ RedisPlayground.sln # Solution file
| ๐ฅ Category | ๐ Features | ๐ก Use Cases | ๐จ Examples |
|---|---|---|---|
| ๐ง Basic | Cache, Strings | Session storage, counters | User sessions, page views |
| ๐ Collections | Lists, Sets, Sorted Sets, Hashes | Queues, leaderboards, profiles | Gaming scores, social feeds |
| โก Advanced | Pub/Sub, Streams, Geospatial | Real-time messaging, location | Chat apps, delivery tracking |
| ๐ Modern | JSON, Bitfields, Analytics | Document storage, ML features | Content management, recommendations |
| ๐ ๏ธ Tools | Locks, Rate Limiting, DevOps | Distributed systems, monitoring | API protection, diagnostics |
sequenceDiagram
participant C as ๐ค Client
participant A as ๐ API Service
participant R as ๐ฆ Redis
participant M as ๐ Monitoring
C->>A: HTTP Request
A->>R: Redis Operation
R-->>A: Data Response
A->>M: Telemetry
A-->>C: JSON Response
Note over A,R: Aspire handles<br/>service discovery
Note over M: OpenTelemetry<br/>observability
|
|
# ๐ฏ One-command startup with full observability
git clone https://github.com/fkucukkara/RedisPlayground.git
cd RedisPlayground
dotnet run --project RedisPlayground.AppHost| ๐๏ธ Service | ๐ URL | ๐ Description |
|---|---|---|
| ๐๏ธ Aspire Dashboard | http://localhost:15000 | Service orchestration & monitoring |
| ๐ API Documentation | Check dashboard for URL + /swagger |
Interactive OpenAPI docs |
| ๐งช HTTP Test Files | VS Code โ HttpTests/*.http |
Ready-to-run API tests |
๐ง Click to expand manual setup instructions
# ๐ณ Start Redis container
docker run -d -p 6379:6379 --name redis-playground redis:latest
# ๐ Run API service directly
dotnet run --project RedisPlayground.ApiService๐ Manual Access: API available at http://localhost:5528
Run this quick test to verify everything is working:
# ๐งช Test basic cache operation
curl -X POST "http://localhost:5528/cache/hello" \
-H "Content-Type: application/json" \
-d '"World"'
# ๐ Retrieve cached value
curl "http://localhost:5528/cache/hello"Expected Response: "World"
๐ฆ Basic Cache & Strings
# ๐๏ธ Distributed Cache (IDistributedCache)
GET /cache/{key} # Retrieve cached value
POST /cache/{key} # Store with 5min TTL
DELETE /cache/{key} # Remove from cache
# ๐ค String Operations & Counters
GET /strings/{key} # Get string value
POST /strings/{key} # Set string value
POST /strings/{key}/increment # Atomic increment/decrement
GET /strings/{key}/length # Get string length๐ Collections & Data Structures
# ๐๏ธ Hash Operations (Key-Value maps)
GET /hashes/{key} # Get all hash fields
POST /hashes/{key}/{field} # Set hash field
GET /hashes/{key}/{field} # Get specific field
# ๐ List Operations (Queues & Stacks)
GET /lists/{key} # Get list range
POST /lists/{key}/push # Push to list
POST /lists/{key}/pop # Pop from list
# ๐ฏ Set Operations (Unique collections)
GET /sets/{key} # Get set members
POST /sets/{key}/add # Add to set
POST /sets/{key}/union # Set union operation
# ๐ Sorted Set Operations (Leaderboards)
GET /sorted-sets/{key}/leaderboard # Get rankings by score
POST /sorted-sets/{key}/add # Add scored member
GET /sorted-sets/{key}/rank/{member} # Get member rankโก Real-time & Streaming
# ๐ก Pub/Sub Messaging
POST /pubsub/publish/{channel} # Publish message to channel
GET /pubsub/subscribe/{channel} # Subscribe to channel (SSE)
GET /pubsub/channels # List active channels
# ๐ Redis Streams (Event sourcing)
POST /streams/{stream}/add # Add entry to stream
GET /streams/{stream}/read # Read stream entries
POST /streams/{stream}/group/create # Create consumer group๐ Location & Spatial
# ๐ Geospatial Operations
POST /geo/{key}/add # Add location with coordinates
GET /geo/{key}/radius # Find points within radius
GET /geo/{key}/distance # Calculate distance between points
GET /geo/{key}/nearby # Get nearby locations๐ Modern Redis Stack
# ๐ JSON Document Operations
GET /json/{key} # Get JSON document
POST /json/{key}/set # Set JSON document
POST /json/{key}/path # JSONPath operations
GET /json/{key}/keys # Get document keys
# ๐ฌ Analytics & Probabilistic Data
POST /analytics/bloom/{key}/add # Bloom filter operations
GET /analytics/bloom/{key}/check # Check bloom filter membership
POST /analytics/hyperloglog/{key}/add # HyperLogLog cardinality๐ง Utilities & Diagnostics
# ๐ฒ Sample Data Generation
POST /devtools/sample-data/generate # Create comprehensive test data
POST /devtools/sample-data/users # Generate user profiles
POST /devtools/sample-data/leaderboard # Generate gaming leaderboard
# ๐๏ธ Database Management
DELETE /devtools/keys/pattern # Bulk delete by pattern
GET /devtools/keys/info # Database statistics & memory usage
GET /devtools/keys/scan # Scan keys by pattern
POST /devtools/backup # Create data backup
# ๐ Direct Redis Access
POST /devtools/command # Execute raw Redis commands
GET /devtools/config # Get Redis configuration
POST /devtools/monitor # Monitor Redis commands (real-time)๐ก Click to see sample API responses
// GET /sorted-sets/leaderboard/top
{
"success": true,
"data": [
{"member": "player1", "score": 2500.0, "rank": 1},
{"member": "player2", "score": 2350.0, "rank": 2},
{"member": "player3", "score": 2100.0, "rank": 3}
],
"metadata": {
"totalMembers": 150,
"timestamp": "2025-08-30T10:30:00Z"
}
}
// GET /geo/stores/nearby
{
"success": true,
"data": [
{
"name": "Store A",
"distance": "0.8 km",
"coordinates": [40.7589, -73.9851]
}
]
}| ๐ Step | ๐ฏ Action | ๐ก Details |
|---|---|---|
| 1 | Install REST Client extension | VS Code marketplace |
| 2 | Open any .http file in HttpTests/ |
15 comprehensive test collections |
| 3 | Click "Send Request" | Above any HTTP request |
| 4 | View responses | In adjacent panel |
๐๏ธ Generate Comprehensive Test Data
# ๐ฏ Generate complete dataset (all Redis types)
curl -X POST "http://localhost:5528/devtools/sample-data/generate" \
-H "Content-Type: application/json" \
-d '{
"keyPrefix": "demo",
"count": 50,
"includeUsers": true,
"includeLeaderboard": true,
"includeGeoData": true
}'๐ This creates:
- โ Cache entries - Session-like data
- โ String counters - Page views, likes
- โ Hash profiles - User information
- โ List queues - Message queues
- โ Set collections - Tags, categories
- โ Sorted leaderboards - Gaming scores
- โ Geospatial data - Store locations
- โ JSON documents - Product catalogs
- โ Stream events - Activity logs
๐๏ธ Cleanup & Reset Operations
# ๐งน Clean up test data by pattern
curl -X DELETE "http://localhost:5528/devtools/keys/pattern" \
-H "Content-Type: application/json" \
-d '{"pattern": "demo:*"}'
# ๐ Check database statistics
curl "http://localhost:5528/devtools/keys/info"
# ๐ Scan for specific patterns
curl "http://localhost:5528/devtools/keys/scan?pattern=user:*&count=10"๐ Gaming Leaderboard Test
# 1๏ธโฃ Add players to leaderboard
curl -X POST "http://localhost:5528/sorted-sets/game-scores/add" \
-H "Content-Type: application/json" \
-d '{"member": "player1", "score": 2500}'
# 2๏ธโฃ Get top 10 players
curl "http://localhost:5528/sorted-sets/game-scores/leaderboard?count=10"
# 3๏ธโฃ Get player rank
curl "http://localhost:5528/sorted-sets/game-scores/rank/player1"๐ Location Services Test
# 1๏ธโฃ Add store locations
curl -X POST "http://localhost:5528/geo/stores/add" \
-H "Content-Type: application/json" \
-d '{
"member": "store1",
"longitude": -73.9851,
"latitude": 40.7589
}'
# 2๏ธโฃ Find nearby stores (within 5km)
curl "http://localhost:5528/geo/stores/radius?longitude=-73.9800&latitude=40.7500&radius=5&unit=km"๐ฌ Real-time Messaging Test
# 1๏ธโฃ Publish message to channel
curl -X POST "http://localhost:5528/pubsub/publish/chat-room" \
-H "Content-Type: application/json" \
-d '{"message": "Hello, Redis!", "user": "demo-user"}'
# 2๏ธโฃ Subscribe to channel (Server-Sent Events)
curl "http://localhost:5528/pubsub/subscribe/chat-room"๐ง Automatic Service Discovery & Orchestration
// AppHost.cs - Zero-configuration Redis setup
var builder = DistributedApplication.CreateBuilder(args);
// ๐ณ Automatic Redis container provisioning
var redis = builder.AddRedis("cache")
.WithRedisCommander(); // Optional: Redis GUI
// ๐ API service with automatic Redis connection
var apiService = builder.AddProject<Projects.RedisPlayground_ApiService>("apiservice")
.WithReference(redis) // Service discovery
.WithReplicas(2); // Load balancing
// ๐๏ธ Aspire dashboard with full observability
builder.Build().Run();โจ Benefits:
- ๐ Automatic service discovery
- ๐ Built-in observability & metrics
- ๐ณ Container lifecycle management
- ๐ง Configuration management
- ๐ Zero manual setup required
๐ง Traditional Connection Setup
{
"ConnectionStrings": {
"cache": "localhost:6379"
},
"Redis": {
"Configuration": {
"AbortOnConnectFail": false,
"ConnectTimeout": 5000,
"SyncTimeout": 5000,
"AsyncTimeout": 5000,
"ConnectRetry": 3,
"KeepAlive": 180
}
},
"Logging": {
"LogLevel": {
"Default": "Information",
"StackExchange.Redis": "Warning"
}
}
}// Manual Redis registration (without Aspire)
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration.GetConnectionString("cache");
options.InstanceName = "RedisPlayground";
});
// Direct StackExchange.Redis registration
builder.Services.AddSingleton<IConnectionMultiplexer>(provider =>
{
var connectionString = builder.Configuration.GetConnectionString("cache");
return ConnectionMultiplexer.Connect(connectionString);
});๐๏ธ Container Orchestration without Aspire
# docker-compose.yml
version: '3.8'
services:
redis:
image: redis:7-alpine
ports:
- "6379:6379"
command: redis-server --appendonly yes
volumes:
- redis-data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 3s
retries: 3
redis-commander:
image: rediscommander/redis-commander:latest
ports:
- "8081:8081"
environment:
- REDIS_HOSTS=local:redis:6379
depends_on:
- redis
api:
build: .
ports:
- "5528:8080"
environment:
- ConnectionStrings__cache=redis:6379
depends_on:
- redis
volumes:
redis-data:๐ Start with: docker-compose up -d
| ๐ง Variable | ๐ Description | ๐ฏ Default |
|---|---|---|
ConnectionStrings__cache |
Redis connection string | localhost:6379 |
ASPNETCORE_ENVIRONMENT |
Runtime environment | Development |
Redis__InstanceName |
Redis instance identifier | RedisPlayground |
OTEL_EXPORTER_OTLP_ENDPOINT |
OpenTelemetry endpoint | (disabled) |
|
|
๐จ Recommended VS Code Extensions
| ๐ง Extension | ๐ Purpose | ๐ฏ Usage |
|---|---|---|
| REST Client | HTTP testing | Test .http files directly in VS Code |
| C# Dev Kit | .NET development | IntelliSense, debugging, project management |
| Docker | Container management | Manage Redis containers |
| Thunder Client | API testing | Alternative to Postman |
| GitLens | Git integration | Enhanced git capabilities |
๐ Redis GUI Tools
| ๐จ Tool | ๐ Features | ๐ฐ Cost |
|---|---|---|
| Redis Commander | Web-based, simple interface | Free |
| RedisInsight | Official Redis GUI, advanced features | Free |
| Medis | macOS native app | Free |
| Redis Desktop Manager | Cross-platform, feature-rich | Paid |
flowchart TD
A[๐ฏ Start Here] --> B[๐ Redis Basics]
B --> C[๐ง .NET Integration]
C --> D[๐๏ธ Aspire Setup]
D --> E[๐งช Test with Playground]
E --> F[๐ Build Your App]
B --> B1[Strings & Cache]
B --> B2[Lists & Sets]
B --> B3[Hashes & Sorted Sets]
C --> C1[StackExchange.Redis]
C --> C2[IDistributedCache]
C --> C3[Dependency Injection]
D --> D1[Service Discovery]
D --> D2[Container Orchestration]
D --> D3[Observability]
style A fill:#e1f5fe
style F fill:#e8f5e8
| ๐ Platform | ๐ฏ Purpose | ๐ Link |
|---|---|---|
| GitHub Issues | Bug reports, feature requests | Create Issue |
| Redis Community | Redis-specific help | Redis Discord |
| .NET Community | .NET & Aspire support | .NET Discord |