Skip to content

A comprehensive .NET 9 demonstration of Redis operations using clean architecture with Microsoft Aspire.

License

Notifications You must be signed in to change notification settings

fkucukkara/redis-playground

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

10 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿš€ Redis Playground

A Modern .NET 9 Redis Operations Showcase

.NET Redis Aspire Docker

Comprehensive Redis operations demonstration with clean architecture, Microsoft Aspire orchestration, and modern .NET patterns


๐Ÿ“‹ Navigation

๐Ÿ—‚๏ธ Table of Contents

โœจ Overview

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.

๐Ÿ—๏ธ Technology Stack

Component Technology
Runtime .NET 9 with Minimal APIs
Orchestration Microsoft Aspire
Redis Client StackExchange.Redis
Documentation OpenAPI/Swagger
Architecture Clean Architecture

๐Ÿ“ฆ Feature Categories

๐ŸŽฏ Category ๐Ÿ“Š Features
Core Cache, Strings, Collections
Real-time Pub/Sub, Streams
Spatial Geospatial Operations
Modern JSON, Analytics, ML
Tools Locks, Utilities, DevOps

๐ŸŒŸ Project Architecture

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
Loading
๐Ÿ“ 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

๐Ÿ—๏ธ Architecture

๐ŸŽฏ Redis Feature Matrix

๐Ÿ”ฅ 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

๐ŸŒŠ Data Flow Architecture

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
Loading

โšก Quick Start

๐Ÿ“‹ Prerequisites

โœ… Required

  • ๐Ÿ”ง .NET 9 SDK
  • ๐Ÿณ Docker Desktop
  • ๐Ÿ’ป Git (for cloning)

๐ŸŒŸ Recommended

  • ๐ŸŽจ VS Code with REST Client
  • ๐Ÿ” Redis CLI tools
  • ๐Ÿ“Š Aspire Dashboard browser

๐Ÿš€ Option 1: Aspire Orchestration (Recommended)

# ๐ŸŽฏ One-command startup with full observability
git clone https://github.com/fkucukkara/RedisPlayground.git
cd RedisPlayground
dotnet run --project RedisPlayground.AppHost

๐ŸŒ Access Points

๐ŸŽ›๏ธ 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

โš™๏ธ Option 2: Manual Setup (Development)

๐Ÿ”ง 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


โœจ Quick Validation

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"

๐Ÿ“– API Reference

๐Ÿ”ง Core Operations

๐Ÿ“ฆ 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

๐Ÿš€ Advanced Features

โšก 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

๐Ÿ› ๏ธ Developer Tools

๐Ÿ”ง 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)

๐Ÿ“ฑ Response Examples

๐Ÿ’ก 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]
    }
  ]
}

๐Ÿงช Testing

๐ŸŽฏ Interactive Testing with HTTP Files

๐Ÿ“ 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

๐ŸŽฒ Sample Data Generation

๐Ÿ—๏ธ 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

๐Ÿงน Data Management

๐Ÿ—‘๏ธ 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"

๐ŸŽฎ Example Test Scenarios

๐Ÿ† 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"

โš™๏ธ Configuration

๐ŸŽฏ Aspire Integration (Recommended)

๐Ÿ”ง 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

โš™๏ธ Manual Configuration (Development)

๐Ÿ”ง Traditional Connection Setup

๐Ÿ“ appsettings.json

{
  "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"
    }
  }
}

๐Ÿ”ง Program.cs Service Registration

// 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);
});

๐Ÿณ Docker Compose Setup (Alternative)

๐Ÿ—๏ธ 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


๐ŸŒ Environment Variables

๐Ÿ”ง 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)

๐Ÿ“š Resources

๐Ÿ“– Official Documentation

๐Ÿ“– Redis Resources

  • ๐ŸŽฏ Redis Data Types Overview
    Complete guide to all Redis data structures

    • Basic Types: Strings, Lists, Sets, Hashes, Sorted Sets
    • Advanced Types: Streams, Geospatial, Bitmaps, Bitfields
    • Modern Features: JSON documents, Vector sets (AI/ML)
    • Probabilistic: HyperLogLog, Bloom filters, t-digest, Count-min sketch
    • Time Series: Specialized timestamped data structures
  • ๐Ÿš€ Redis Commands Reference
    Comprehensive command documentation

  • ๐ŸŽ“ Redis University
    Free courses and certifications

๐Ÿ—๏ธ .NET Aspire Resources

  • ๐ŸŒŸ .NET Aspire Integrations Overview
    Cloud-native development platform

    • Hosting Integrations: Container & cloud resource provisioning
    • Client Integrations: DI, health checks, telemetry automation
    • Redis Packages:
      • Aspire.StackExchange.Redis - Core operations
      • Aspire.StackExchange.Redis.DistributedCaching - IDistributedCache
      • Aspire.StackExchange.Redis.OutputCaching - Response caching
    • Service Defaults: Observability, health, resiliency patterns
  • ๐ŸŽฏ Aspire Dashboard
    Observability & monitoring


๐Ÿ› ๏ธ Developer Tools & Extensions

๐ŸŽจ 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

๐ŸŽ“ Learning Path

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
Loading

๐Ÿค Community & Support

๐ŸŒ 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

๐ŸŒŸ Star this repo if it helped you!

GitHub stars GitHub forks

Made with โค๏ธ for the .NET & Redis communities


๐Ÿ“„ MIT License*

About

A comprehensive .NET 9 demonstration of Redis operations using clean architecture with Microsoft Aspire.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages