https://github.com/fkucukkara/redisplayground
A comprehensive .NET 9 demonstration of Redis operations using clean architecture with Microsoft Aspire.
https://github.com/fkucukkara/redisplayground
api-rest architecture aspire aspire-dotnet claude-sonnet-4 copilot dotnet-core geo hashes json lists pub-sub redis streams
Last synced: about 1 month ago
JSON representation
A comprehensive .NET 9 demonstration of Redis operations using clean architecture with Microsoft Aspire.
- Host: GitHub
- URL: https://github.com/fkucukkara/redisplayground
- Owner: fkucukkara
- License: mit
- Created: 2025-08-30T15:34:19.000Z (about 1 month ago)
- Default Branch: main
- Last Pushed: 2025-08-30T17:07:18.000Z (about 1 month ago)
- Last Synced: 2025-08-30T17:40:04.612Z (about 1 month ago)
- Topics: api-rest, architecture, aspire, aspire-dotnet, claude-sonnet-4, copilot, dotnet-core, geo, hashes, json, lists, pub-sub, redis, streams
- Language: C#
- Homepage:
- Size: 57.6 KB
- Stars: 1
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# ๐ Redis Playground
### *A Modern .NET 9 Redis Operations Showcase*
[](https://dotnet.microsoft.com/)
[](https://redis.io/)
[](https://learn.microsoft.com/en-us/dotnet/aspire/)
[](https://www.docker.com/)**Comprehensive Redis operations demonstration with clean architecture, Microsoft Aspire orchestration, and modern .NET patterns**
---
## ๐ Navigation
๐๏ธ Table of Contents
- [โจ Overview](#-overview)
- [๐๏ธ Architecture](#๏ธ-architecture)
- [โก Quick Start](#-quick-start)
- [๐ API Reference](#-api-reference)
- [๐งช Testing](#-testing)
- [โ๏ธ Configuration](#๏ธ-configuration)
- [๐ Resources](#-resources)## โจ 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**
```mermaid
graph TB
A[๐ฏ AppHost
Aspire Orchestration] --> B[๐ ApiService
Main API]
A --> C[๐ฆ Redis Container
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
```## ๐๏ธ 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**
```mermaid
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
service discovery
Note over M: OpenTelemetry
observability
```## โก 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)*
```bash
# ๐ฏ 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
```bash
# ๐ณ 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:
```bash
# ๐งช 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
```http
# ๐๏ธ 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
```http
# ๐๏ธ 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
```http
# ๐ก 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
```http
# ๐ 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
```http
# ๐ 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
```http
# ๐ฒ 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
```json
// 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
```bash
# ๐ฏ 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
```bash
# ๐งน 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
```bash
# 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
```bash
# 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
```bash
# 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
```csharp
// 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("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**
```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**
```csharp
// 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(provider =>
{
var connectionString = builder.Configuration.GetConnectionString("cache");
return ConnectionMultiplexer.Connect(connectionString);
});
```---
### ๐ณ **Docker Compose Setup** *(Alternative)*
๐๏ธ Container Orchestration without Aspire
```yaml
# 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: 3redis-commander:
image: rediscommander/redis-commander:latest
ports:
- "8081:8081"
environment:
- REDIS_HOSTS=local:redis:6379
depends_on:
- redisapi:
build: .
ports:
- "5528:8080"
environment:
- ConnectionStrings__cache=redis:6379
depends_on:
- redisvolumes:
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](https://redis.io/docs/latest/develop/data-types/)**
*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](https://redis.io/commands/)**
*Comprehensive command documentation*- ๐ **[Redis University](https://university.redis.com/)**
*Free courses and certifications*#### ๐๏ธ **.NET Aspire Resources**
- ๐ **[.NET Aspire Integrations Overview](https://learn.microsoft.com/en-us/dotnet/aspire/fundamentals/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](https://learn.microsoft.com/en-us/dotnet/aspire/fundamentals/dashboard/overview)**
*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**
```mermaid
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
```---
### ๐ค **Community & Support**
| ๐ **Platform** | ๐ฏ **Purpose** | ๐ **Link** |
|------------------|----------------|-------------|
| **GitHub Issues** | Bug reports, feature requests | [Create Issue](https://github.com/fkucukkara/RedisPlayground/issues) |
| **Discussions** | Questions, ideas, showcases | [Join Discussion](https://github.com/fkucukkara/RedisPlayground/discussions) |
| **Redis Community** | Redis-specific help | [Redis Discord](https://discord.gg/redis) |
| **.NET Community** | .NET & Aspire support | [.NET Discord](https://discord.gg/dotnet) |---
### ๐ **Star this repo if it helped you!**
[](https://github.com/fkucukkara/RedisPlayground/stargazers)
[](https://github.com/fkucukkara/RedisPlayground/network)**Made with โค๏ธ for the .NET & Redis communities**
---
*๐ Want to contribute? Check our [Contributing Guidelines](CONTRIBUTING.md) | ๐ [MIT License](LICENSE)*