Thanks to visit codestin.com
Credit goes to github.com

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

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