RRedis Handbook

TEMEL

Kurulum & Bağlantı

Redis 8 ve .NET 10 ile caching, veri yapıları, messaging, ölçekleme, dayanıklılık ve production operasyonları.

Kod örneği görünümü Bu sayfadaki eşleşen örnekleri seçilen istemciye göre gösterir.

Redis Server

# docker-compose.yml
services:
  redis:
    image: redis:8-alpine
    ports:
      - "6379:6379"
    command: redis-server --appendonly yes --maxmemory 256mb --maxmemory-policy allkeys-lru
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 3s
      retries: 3
    volumes:
      - redis-data:/data

  redis-insight:
    image: redis/redisinsight:latest
    ports:
      - "5540:5540"
    depends_on:
      - redis
    # Browser'dan http://localhost:5540 → Add Database → redis:6379

volumes:
  redis-data:

Redis Insight: Web tabanlı GUI — key browse, memory analiz, slow query, profiling. Junior'lar için Redis'ı görsel keşfetme aracı. Production'da kullanma, sadece dev/test.

.NET Paketleri

dotnet add package StackExchange.Redis
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis

Bağlantı Yönetimi

redis-cli -h localhost -p 6379
# AUTH password
# SELECT 0

PING    # PONG
INFO server
INFO memory
// Program.cs — ConnectionMultiplexer (Singleton)
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
{
    var config = ConfigurationOptions.Parse(
        builder.Configuration.GetConnectionString("Redis")!);
    config.AbortOnConnectFail = false;
    config.ConnectRetry = 3;
    config.ConnectTimeout = 5000;
    config.SyncTimeout = 3000;
    config.AsyncTimeout = 3000;
    config.ReconnectRetryPolicy = new ExponentialRetry(5000);
    return ConnectionMultiplexer.Connect(config);
});

// IDistributedCache — Microsoft abstraction
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration.GetConnectionString("Redis");
    options.InstanceName = "myapp:";
});

// IDatabase elde etme (her yerde)
public class ProductService
{
    private readonly IDatabase _redis;

    public ProductService(IConnectionMultiplexer mux)
    {
        _redis = mux.GetDatabase();
    }
}
// appsettings.json
{
  "ConnectionStrings": {
    "Redis": "localhost:6379,abortConnect=false,connectRetry=3,connectTimeout=5000"
  }
}

ConnectionMultiplexer mutlaka Singleton olmalı. Her request'te yeni bağlantı açmak anti-pattern'dır. Multiplexer binlerce concurrent çağrıyı tek TCP bağlantısı üzerinden yönetir. Multi-DB kullansan bile (GetDatabase(0), GetDatabase(1)...) aynı Singleton multiplexer'ı paylaşırsın — GetDatabase(n) yeni connection açmaz, sadece o DB'ye SELECT gönderilmesini sağlayan lightweight bir wrapper döner.

Connection String Parametreleri

Parametre Varsayılan Açıklama
abortConnect true false yap — bağlanamayınca hata fırlatmaz, retry eder
connectRetry 3 Bağlantı retry sayısı
connectTimeout 5000 Bağlantı timeout (ms)
syncTimeout 5000 Senkron komut timeout (ms)
asyncTimeout 5000 Asenkron komut timeout (ms)
ssl false TLS aktifleştir
password Redis şifresi
defaultDatabase 0 Varsayılan DB index

Key Naming Conventions

Kural Örnek Açıklama
Colon separator user:1001:profile Hiyerarşik namespace
Lowercase cache:product:123 Tutarlılık, case-sensitive hata önleme
Kısa ama anlamlı sess:abc123 Memory tasarrufu (key name RAM'de tutulur)
Prefix ile amaç cache:, lock:, queue:, rate: Hangi pattern'a ait olduğu belli
ID son segment order:5432 SCAN pattern: order:*
Hash tag (Cluster) {user:1001}:profile Aynı slot'a düşür, multi-key ops
TTL ipucu (opsiyonel) tmp:import:batch42 Geçici key olduğu belli
# Pattern: {service}:{entity}:{id}:{field}
cache:product:123             # string cache
cache:product:123:reviews     # alt veri
user:1001:settings            # hash
lock:order-process:5432       # distributed lock
rate:api:192.168.1.1          # rate limit counter
queue:emails                  # list/stream
sess:abc123                   # session hash
uv:2026-05-27                 # HyperLogLog (unique visitors)

Max key length: 512MB teorik limit ama kısa tut. Her key ~50 byte overhead (ptr + metadata). 1M key × 100 byte key name = ~100MB sadece key'ler için.

Cluster'a hazırlık: Baştan key prefix kullan (cache:, session:). Multi-DB yerine prefix → Cluster migration'da sıfır değişiklik.