Skip to content

Latest commit

 

History

History
354 lines (267 loc) · 16.2 KB

README.tr.md

File metadata and controls

354 lines (267 loc) · 16.2 KB

CacheDB PostgreSQL Örnek Uygulaması

CacheDB 0.19.4, Redis 8 ve PostgreSQL 16 kullanan çalıştırılabilir Spring Boot 3 ve Java 21 REST API örneği.

English | Türkçe

CacheDB 0.19.4 Java 21+

Hızlı Başlangıç · Maven Kurulumu · Kod Üzerinden Akış · API ve Özellik Örnekleri · Postman Koleksiyonları · Ayrık API ve Worker Modu · Yapılandırma ve Sorun Giderme


Genel Bakış

Bu bağımsız örnek proje, gerçek bir Spring Boot servisinde PostgreSQL kalıcı doğruluk kaynağı olarak korunurken Redis katmanının düşük gecikmeli ve bellek-sınırlı aktif veri katmanı olarak nasıl kullanıldığını gösterir:

  • Derleme zamanında üretilen @CacheRepository arayüzleri — entity, projection, warm planları ve SQL arşiv yolları için sıfır çalışma zamanı reflection maliyeti.
  • Ekran odaklı projection modelleri (@CacheProjectionRecord) — N+1 ilişki sorgularına girmeden imleç (cursor) tabanlı hızlı listeler ve panolar.
  • Sürüm korumalı write-behind — Redis'e kabul edilen yazmaların arka planda güvenli ve toplu biçimde PostgreSQL veritabanına aktarılması.
  • Güncel 0.19 yetenekleri — Spring Data keyset sayfalama, Spring @Cacheable metot önbellekleme, CompletableFuture ve Project Reactor adaptörleri, CountFacetReadModel stok panosu, @CacheRetention saklama politikaları ve isteğe bağlı @CacheEncrypted alan şifreleme.

Ön Koşullar

  • Java 21+
  • Maven 3.9+
  • Docker ve Docker Compose

GitHub token'ı, özel settings.xml ayarı veya yerel CacheDB kaynak kodu derlemesi gerekmez; Maven 0.19.4 paketlerini doğrudan herkese açık depodan indirir.


Hızlı Başlangıç

1. Redis ve PostgreSQL Servislerini Başlatın

docker compose up -d
docker compose ps
Servis Yerel Adres Görevi
Redis 8 127.0.0.1:56379 Aktif entity'ler, projection'lar, bileşik indeksler ve iş koordinasyonu
PostgreSQL 16 127.0.0.1:55432 Kalıcı SQL doğruluk kaynağı

2. Uygulamayı demo Profiliyle Çalıştırın

Bash / macOS / Linux:

SPRING_PROFILES_ACTIVE=demo mvn spring-boot:run

PowerShell (Windows):

$env:SPRING_PROFILES_ACTIVE = "demo"
mvn spring-boot:run

3. Örnek Veri Oluşturun, Projection Isıtın ve Sorgulayın

Hazırlık durumunu kontrol edin, örnek verileri oluşturun, 1 numaralı müşterinin sipariş zaman çizelgesi projection'ını Redis'e ısıtın ve sıcak Redis yolu ile sınırlı SQL arşiv yolunu karşılaştırın:

$base = "http://127.0.0.1:8091"

# 1. Uygulama, Redis ve SQL hazırlık kontrolü
Invoke-RestMethod "$base/actuator/health/readiness"

# 2. Örnek müşteri, ürün ve sipariş verisini oluşturun (arka plan işi)
$seed = Invoke-RestMethod -Method Post "$base/api/demo/seed?customers=20&ordersPerCustomer=40&linesPerOrder=4"
do {
    Start-Sleep -Milliseconds 250
    $job = Invoke-RestMethod "$base/api/warm/jobs/$($seed.jobId)"
} while ($job.status -in @("QUEUED", "RUNNING"))

# 3. 1 numaralı müşterinin sipariş projection'ını Redis'e ısıtın
$warm = Invoke-RestMethod -Method Post "$base/api/warm/orders/customer/1?limit=100&projectionOnly=true"
do {
    Start-Sleep -Milliseconds 250
    $job = Invoke-RestMethod "$base/api/warm/jobs/$($warm.jobId)"
} while ($job.status -in @("QUEUED", "RUNNING"))

# 4. Sıcak Redis projection yolunu okuyun (imleçli sayfalama)
Invoke-RestMethod "$base/api/customers/1/orders?limit=10"

# 5. Açık PostgreSQL arşiv yolunu okuyun
Invoke-RestMethod "$base/api/orders/archive?customerId=1&limit=10"

4. Yerleşik Yönetim Panelini Açın

  • Yönetim Paneli: http://127.0.0.1:8091/cachedb-admin
  • Çalışma Zamanı Ayar Özeti: http://127.0.0.1:8091/api/tuning
  • Derlenmiş Route Kataloğu: http://127.0.0.1:8091/actuator/cachedb

İşiniz bittiğinde yerel konteynerleri durdurmak için:

docker compose down

Maven Kurulumu

pom.xml; cachedb-bom, PostgreSQL starter'ı, cachedb-processor ve cachedb-maven-plugin (cachedb:doctor) bileşenlerini 0.19.4 sürümünde eşitler:

<properties>
    <cachedb.version>0.19.4</cachedb.version>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.reactor.cachedb</groupId>
            <artifactId>cachedb-bom</artifactId>
            <version>${cachedb.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>com.reactor.cachedb</groupId>
        <artifactId>cachedb-spring-boot-starter-postgres</artifactId>
    </dependency>
    <dependency>
        <groupId>com.reactor.cachedb</groupId>
        <artifactId>cachedb-annotations</artifactId>
    </dependency>
    <dependency>
        <groupId>com.reactor.cachedb</groupId>
        <artifactId>cachedb-spring-boot-starter-admin</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

<repositories>
    <repository>
        <id>cachedb-public</id>
        <url>https://esasmer-dou.github.io/cache-database/maven2</url>
    </repository>
</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>cachedb-public</id>
        <url>https://esasmer-dou.github.io/cache-database/maven2</url>
    </pluginRepository>
</pluginRepositories>

Kod Üzerinden Akış

1. Entity Eşlemesi (OrderEntity.java)

SQL kolonlarını, Redis isim alanını, bölümlenmiş (partitioned) indeksi ve üst sınırlı bire-çok ilişkiyi tanımlar:

@CacheEntity(table = "sample_orders", redisNamespace = "sample-orders")
@CachePartitionedIndex(partitionBy = "customer_id", sortBy = "order_date")
public class OrderEntity {
    @CacheId(column = "order_id")
    public Long orderId;

    @CacheColumn("customer_id")
    public Long customerId;

    @CacheColumn("order_date")
    public Long orderDate;

    @CacheRelation(
            target = OrderLineEntity.class,
            mappedBy = "orderId",
            kind = CacheRelation.RelationKind.ONE_TO_MANY,
            batchLoadOnly = true,
            maxRowsPerParent = 50,
            parentBatchSize = 16,
            orderBy = "lineNumber ASC"
    )
    public List<OrderLineEntity> lines;
}

2. Küçük Okuma Modeli (OrderSummary.java)

Zaman çizelgesi ve sıralama ekranlarının ihtiyaç duyduğu özet alanları tutar:

@CacheProjectionRecord(
        source = OrderEntity.class,
        id = "orderId",
        name = "order-summary",
        rankedBy = {"order_date", "priority_score"},
        refresh = CacheProjectionRecord.Refresh.ASYNC
)
public record OrderSummary(
        Long orderId,
        Long customerId,
        Long orderDate,
        BigDecimal orderAmount,
        String currencyCode,
        String orderType,
        String status,
        Integer lineCount,
        Double priorityScore
) {}

3. Deklaratif Repository (OrderRepository.java)

Hem sıcak Redis projection yolunu hem de onun warm planını derleme anında denetlenen tek bir arayüzde toplar:

@CacheRepository(entity = OrderEntity.class)
public interface OrderRepository extends CacheDbRepository<OrderEntity, Long> {

    @HotRoute(
            value = "customer-order-timeline",
            projection = OrderSummary.class,
            pageSize = 100,
            hotWindow = 1_000,
            coverageScopeParameter = "customerId"
    )
    @CacheRouteQuery(
            predicates = {
                    @CachePredicate(field = "customerId"),
                    @CachePredicate(field = "status", operator = CachePredicate.Operator.NE, constants = "DELETED")
            },
            orderBy = {
                    @CacheOrder(field = "orderDate", direction = CacheOrder.Direction.DESC),
                    @CacheOrder(field = "orderId", direction = CacheOrder.Direction.DESC)
            }
    )
    CursorPage<OrderSummary> customerTimeline(long customerId, WindowRequest window);

    @WarmRoute(value = "warm-customer-order-timeline", from = "customerTimeline", maxRows = 1_000)
    CacheWarmPlan warmCustomerTimeline(long customerId, int maxRows, CacheWarmTarget target);
}

API ve Özellik Örnekleri

Temel İş Alanı Uç Noktaları

Alan Örnek Uç Noktalar Veri Yolu
Müşteriler POST /api/customers, GET /api/customers/{id}, GET /api/customers/{id}/orders Write-behind yazma, Redis tekil okuma, Redis projection zaman çizelgesi
Siparişler POST /api/orders, GET /api/orders/high-value, GET /api/orders/archive Write-behind yazma, sıralı projection, sınırlı PostgreSQL arşiv yolu
Ürünler ve Katalog GET /api/products/active, POST /api/catalog/refresh, GET /api/catalog/categories/{category} Projection'lar ve tipli katalog snapshot'ları
Sevkiyat ve Destek GET /api/shipments/active, GET /api/shipments/archive, GET /api/tickets/open Sıcak operasyonel pencereler ve SQL arşiv sorguları
Warm ve Operasyon POST /api/warm/..., GET /api/warm/jobs/{jobId}, GET /api/warm/schedules Dağıtık Redis lider kilitli warm ve uzlaştırma işleri

Öne Çıkan 0.19 Özellik Senaryoları (demo Profili)

Uygulama SPRING_PROFILES_ACTIVE=demo ile başlatıldığında (demo-shop-a, demo-shop-b veya demo-supplier demo Bearer anahtarlarıyla), yeni çatı yeteneklerini gösteren uç noktalar da aktif olur:

Yetenek Örnek Uç Noktalar Kaynak Paketi
Stok Panosu (CountFacetReadModel) POST /api/examples/v019/stock-dashboard/refresh, GET /api/examples/v019/stock-dashboard dashboard
Bileşik Aralık ve Spring Data Keyset PUT/GET /api/examples/v019/range-data/{run}/rows/{slot}, GET .../native, GET .../data/page, GET .../data/window rangedata
Spring @Cacheable, Asenkron ve Reactor GET /api/examples/v019/cache/quotes/{sku}, PUT/GET /api/examples/v019/async/offers/{id}, GET /api/examples/v019/reactive/stock/{id} cacheapi
Yakın Önbellek (L1), Facet ve Causal Okuma PUT/GET /api/examples/v018/offers/{id}, PUT /api/examples/v018/stock/{id} (X-CacheDB-Causal) controls
Saklama Politikası (EVICT_CACHE / DELETE) ve Toplu Silme PUT /api/examples/v019/audit-notes/{policy}/{slot}, POST .../sweep, POST .../delete/bulk audit

İsteğe Bağlı Profil: Alan Düzeyinde Şifreleme (@CacheEncrypted)

Açık 256-bit anahtarlarla AES-GCM alan şifrelemesini (EncryptionScope.REDIS_ONLY) denemek için:

$bytes = [byte[]]::new(32)
[Security.Cryptography.RandomNumberGenerator]::Fill($bytes); $env:SAMPLE_ENCRYPTION_AES_KEY = [Convert]::ToBase64String($bytes)
[Security.Cryptography.RandomNumberGenerator]::Fill($bytes); $env:SAMPLE_ENCRYPTION_HMAC_KEY = [Convert]::ToBase64String($bytes)

mvn -Pencrypted-demo clean spring-boot:run "-Dspring-boot.run.profiles=demo,encryption"

Ardından Authorization: Bearer demo-supplier başlığıyla http://127.0.0.1:8091/api/examples/v019/encryption/notes/1 adresine PUT ve GET istekleri gönderebilirsiniz.


Postman Koleksiyonları

postman/ dizinindeki hazır koleksiyonları Postman'e aktararak http://127.0.0.1:8091 üzerinde tüm akışları etkileşimli olarak deneyebilirsiniz:

Koleksiyon Kapsam
cache-database-postgresql-sample.postman_collection.json Uçtan uca iş API'si, seed/warm akışları, Spring Cache, asenkron ve Reactor uç noktaları
cache-database-postgresql-catalog.postman_collection.json Tipli katalog snapshot'ları ve idempotent tedarikçi toplu aktarımları
cache-database-postgresql-v018.postman_collection.json Toplu L1 okumalar, soft-TTL yenileme, facet'ler, tenant bölümleri ve causal token'lar
cache-database-postgresql-range-data.postman_collection.json 64-bit Long bileşik aralık sorguları ve Spring Data Page / Slice / Window
stock-dashboard-v019.postman_collection.json Tenant izoleli CountFacetReadModel yenileme ve sıfır-SQL pano okumaları
cache-database-postgresql-audit.postman_collection.json @CacheRetention önbellek düşürme / write-behind silme ve sınırlı toplu silme
cache-database-postgresql-encryption.postman_collection.json @CacheEncrypted alan şifreleme akışı (yukarıdaki -Pencrypted-demo başlatmasını gerektirir)

Ayrık API ve Worker Modu

Kubernetes veya çoklu konteyner ortamlarında HTTP API sunucularını arka plan write-behind/warm worker'larından ayırmak için docker-compose.roles.yml dosyasını kullanabilirsiniz:

mvn clean package -DskipTests
docker compose -f docker-compose.yml -f docker-compose.roles.yml up -d

Yapılandırma ve Sorun Giderme

Temel Ortam Değişkenleri

Değişken Varsayılan Açıklama
DB_URL jdbc:postgresql://127.0.0.1:55432/cachedb_sample PostgreSQL JDBC bağlantı adresi
DB_USERNAME cachedb Veritabanı kullanıcı adı
REDIS_URI redis://127.0.0.1:56379 Redis bağlantı adresi
SAMPLE_READ_COALESCING_ENABLED false (${SAMPLE_READ_COALESCING_ENABLED:false}) İsteğe bağlı single-flight Redis tekil okuma birleştirme; yoğun eşzamanlı yükte SAMPLE_READ_COALESCING_ENABLED=true ile p99 gecikmesini karşılaştırarak açabilirsiniz

Sorun Giderme

Belirti Çözüm
Sıcak liste uç noktası 503 Service Unavailable döndürüyor İlgili /api/warm/... işini başlatın ve /api/warm/jobs/{jobId} durumu COMPLETED olana kadar bekleyin.
Hazırlık uç noktası DOWN görünüyor docker compose ps çıktısında hem Redis hem PostgreSQL servisinin healthy olduğunu doğrulayın.
/api/demo/seed veya /api/examples/... 404 döndürüyor Uygulamayı SPRING_PROFILES_ACTIVE=demo ile başlattığınızdan emin olun.
İstek 429 Too Many Requests döndürüyor İstek kabul sınırı veya write-behind kuyruk koruması dolmuştur; anlık yükü azaltın veya /api/tuning çıktısını inceleyin.
8091 portu kullanımda Önceki örnek süreci durdurun veya SERVER_PORT ortam değişkeniyle farklı bir port verin.

İlgili Rehberler