Skip to content

Latest commit

 

History

History
354 lines (267 loc) · 15.1 KB

README.md

File metadata and controls

354 lines (267 loc) · 15.1 KB

CacheDB PostgreSQL Sample

Runnable Spring Boot 3 & Java 21 REST API demonstrating CacheDB 0.19.4 with Redis 8 and PostgreSQL 16.

English | Türkçe

CacheDB 0.19.4 Java 21+

Quick Start · Maven Setup · Code Walkthrough · API & Feature Examples · Postman Collections · Split API & Worker Mode · Configuration & Troubleshooting


Overview

This standalone sample shows how a real Spring Boot application uses CacheDB with PostgreSQL as the durable source of truth and Redis as the bounded, low-latency active data layer:

  • Compile-time @CacheRepository interfaces — zero runtime reflection for entities, projections, warm plans, and SQL archive routes.
  • Screen-shaped projections (@CacheProjectionRecord) — fast cursor-paginated timelines and dashboards without N+1 relation queries.
  • Version-fenced write-behind — low-latency Redis writes persisted asynchronously to PostgreSQL.
  • Modern 0.19 capabilities — Spring Data keyset pagination, Spring @Cacheable method caching, CompletableFuture & Project Reactor adapters, CountFacetReadModel dashboards, @CacheRetention policies, and optional @CacheEncrypted field protection.

Prerequisites

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

No GitHub token, custom settings.xml, or local CacheDB framework build is required — Maven downloads 0.19.4 directly from the public repository.


Quick Start

1. Start Redis and PostgreSQL

docker compose up -d
docker compose ps
Service Local Address Role
Redis 8 127.0.0.1:56379 Active entities, projections, composite indexes, and job coordination
PostgreSQL 16 127.0.0.1:55432 Durable SQL source of truth

2. Run the Application (demo Profile)

Bash / macOS / Linux:

SPRING_PROFILES_ACTIVE=demo mvn spring-boot:run

PowerShell (Windows):

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

3. Seed, Warm, and Query

Verify readiness, generate sample data, warm a customer's order timeline projection, and compare the hot Redis route with the bounded SQL archive route:

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

# 1. Check application, Redis, and SQL readiness
Invoke-RestMethod "$base/actuator/health/readiness"

# 2. Seed sample customers, products, and orders (background job)
$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. Warm customer #1's order timeline projection into Redis
$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. Read the hot Redis projection (cursor-paginated)
Invoke-RestMethod "$base/api/customers/1/orders?limit=10"

# 5. Read the explicit PostgreSQL archive route
Invoke-RestMethod "$base/api/orders/archive?customerId=1&limit=10"

4. Open the Built-in Admin Console

  • Admin Dashboard: http://127.0.0.1:8091/cachedb-admin
  • Runtime Tuning Snapshot: http://127.0.0.1:8091/api/tuning
  • Compiled Route Catalog: http://127.0.0.1:8091/actuator/cachedb

To stop local containers when finished:

docker compose down

Maven Setup

pom.xml aligns cachedb-bom, the PostgreSQL starter, cachedb-processor, and cachedb-maven-plugin (cachedb:doctor) at 0.19.4:

<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>

Code Walkthrough

1. Entity Mapping (OrderEntity.java)

Maps SQL columns, a Redis namespace, a partitioned index, and a bounded one-to-many relation:

@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. Compact Read Model (OrderSummary.java)

Stores only the fields needed by timeline and ranking screens:

@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. Declarative Repository (OrderRepository.java)

Declares both the hot Redis projection route and its warm plan in one compile-time checked interface:

@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 & Feature Examples

Core Domain Endpoints

Domain Area Representative Endpoints Data Path
Customers POST /api/customers, GET /api/customers/{id}, GET /api/customers/{id}/orders Write-behind command, Redis entity lookup, Redis projection timeline
Orders POST /api/orders, GET /api/orders/high-value, GET /api/orders/archive Write-behind command, ranked projection, bounded PostgreSQL source route
Products & Catalog GET /api/products/active, POST /api/catalog/refresh, GET /api/catalog/categories/{category} Projections and typed catalog snapshots
Shipments & Support GET /api/shipments/active, GET /api/shipments/archive, GET /api/tickets/open Hot operational windows vs SQL archive routes
Warm & Operations POST /api/warm/..., GET /api/warm/jobs/{jobId}, GET /api/warm/schedules Distributed Redis-leased warm and reconciliation jobs

Highlighted 0.19 Feature Showcases (demo Profile)

When started with SPRING_PROFILES_ACTIVE=demo (using demo bearer tokens demo-shop-a, demo-shop-b, or demo-supplier), the sample also exposes focused examples for newer framework features:

Capability Example Endpoints Source Package
Stock Dashboard (CountFacetReadModel) POST /api/examples/v019/stock-dashboard/refresh, GET /api/examples/v019/stock-dashboard dashboard
Composite Range & Spring Data Keyset PUT/GET /api/examples/v019/range-data/{run}/rows/{slot}, GET .../native, GET .../data/page, GET .../data/window rangedata
Spring @Cacheable, Async & Reactor GET /api/examples/v019/cache/quotes/{sku}, PUT/GET /api/examples/v019/async/offers/{id}, GET /api/examples/v019/reactive/stock/{id} cacheapi
Near Cache, Facets & Causal Reads PUT/GET /api/examples/v018/offers/{id}, PUT /api/examples/v018/stock/{id} (X-CacheDB-Causal) controls
Retention (EVICT_CACHE / DELETE) & Bulk Delete PUT /api/examples/v019/audit-notes/{policy}/{slot}, POST .../sweep, POST .../delete/bulk audit

Optional Profile: Field-Level Encryption (@CacheEncrypted)

To try AES-GCM field encryption (EncryptionScope.REDIS_ONLY) with explicit 256-bit keys:

$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"

Then PUT and GET encrypted notes at http://127.0.0.1:8091/api/examples/v019/encryption/notes/1 with header Authorization: Bearer demo-supplier.


Postman Collections

Import any collection from postman/ into Postman to explore endpoints interactively against http://127.0.0.1:8091:

Collection Focus
cache-database-postgresql-sample.postman_collection.json End-to-end business API, seed/warm flows, Spring Cache, async & Reactor routes
cache-database-postgresql-catalog.postman_collection.json Typed catalog snapshots and idempotent supplier batch imports
cache-database-postgresql-v018.postman_collection.json Bulk L1 reads, soft-TTL refresh, facets, tenant partitions, and causal tokens
cache-database-postgresql-range-data.postman_collection.json 64-bit Long composite range queries and Spring Data Page / Slice / Window
stock-dashboard-v019.postman_collection.json Tenant-isolated CountFacetReadModel refresh and zero-SQL dashboard reads
cache-database-postgresql-audit.postman_collection.json @CacheRetention cache eviction vs write-behind deletion and bounded bulk delete
cache-database-postgresql-encryption.postman_collection.json @CacheEncrypted field-level encryption (requires -Pencrypted-demo startup above)

Split API & Worker Mode

In Kubernetes or multi-container deployments, you can separate stateless HTTP API pods from background write-behind/warm worker pods using docker-compose.roles.yml:

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

Configuration & Troubleshooting

Common Environment Variables

Variable Default Purpose
DB_URL jdbc:postgresql://127.0.0.1:55432/cachedb_sample JDBC connection URL for PostgreSQL
DB_USERNAME cachedb Database username
REDIS_URI redis://127.0.0.1:56379 Redis connection URI
SAMPLE_READ_COALESCING_ENABLED false (${SAMPLE_READ_COALESCING_ENABLED:false}) Opt-in single-flight Redis point-read coalescing; set SAMPLE_READ_COALESCING_ENABLED=true and compare p99 latency under concurrent load

Troubleshooting

Symptom Resolution
Hot list endpoint returns 503 Service Unavailable Run the matching /api/warm/... job and wait until /api/warm/jobs/{jobId} reaches COMPLETED.
Readiness endpoint reports DOWN Confirm docker compose ps shows both Redis and PostgreSQL as healthy.
/api/demo/seed or /api/examples/... returns 404 Start the application with SPRING_PROFILES_ACTIVE=demo.
Request returns 429 Too Many Requests Bounded admission or write-behind queue guardrail is saturated; reduce burst rate or inspect /api/tuning.
Port 8091 is already in use Stop any previous sample process or override SERVER_PORT.

Further Reading