Chuyển đến nội dung chính

第 18 課:快取、運行狀況檢查和 API 網關

使用 @CacheResult 進行 Redis 快取、運行狀況檢查(活躍性/就緒性)、API 閘道模式、速率限制、聚合。

💻 程式設計 — 第 17 課 第 18 課:快取、運行狀況檢查和 API 閘道

Quarkus 微服務:從基礎知識到生產

第 5 部分:彈性和可觀察性

亞洲開發網

簡介

本文透過 3 個橫切關注點完善了微服務平台:Redis 快取減少資料庫負載,用於 Kubernetes 就緒/活躍性探針的運行狀況檢查,以及 API 網關作為前端的單一入口點。

Redis 緩存

依賴關係

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-cache</artifactId>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-redis-cache</artifactId>
</dependency>

配置

# Dev Services tự động start Redis container
# Production:
%prod.quarkus.redis.hosts=redis://localhost:6379
%prod.quarkus.redis.password=${REDIS_PASSWORD}

# Cache TTL
quarkus.cache.redis.product-cache.ttl=5M
quarkus.cache.redis.category-cache.ttl=30M
quarkus.cache.redis.product-list-cache.ttl=2M

@CacheResult — 快取方法返回

import io.quarkus.cache.CacheResult;
import io.quarkus.cache.CacheInvalidate;
import io.quarkus.cache.CacheInvalidateAll;
import io.quarkus.cache.CacheKey;

@ApplicationScoped
public class ProductService {

    // Cache kết quả findById
    @CacheResult(cacheName = "product-cache")
    public ProductDTO getById(@CacheKey Long id) {
        Log.infof("Cache MISS: product %d", id);
        Product product = productRepo.findByIdOptional(id)
            .orElseThrow(() ->
                new ResourceNotFoundException("Product", id));
        return ProductDTO.from(product);
    }

    // Invalidate khi update
    @CacheInvalidate(cacheName = "product-cache")
    @Transactional
    public ProductDTO update(@CacheKey Long id,
                             UpdateProductRequest req) {
        Product product = productRepo.findByIdOptional(id)
            .orElseThrow(() ->
                new ResourceNotFoundException("Product", id));
        // ... update fields ...
        return ProductDTO.from(product);
    }

    // Invalidate khi delete
    @CacheInvalidate(cacheName = "product-cache")
    @Transactional
    public void delete(@CacheKey Long id) {
        productRepo.deleteById(id);
    }

    // Cache list với composite key
    @CacheResult(cacheName = "product-list-cache")
    public List<ProductListDTO> listByCategory(
            @CacheKey String category,
            @CacheKey int page,
            @CacheKey int size) {
        return productRepo
            .findActive(category, null,
                Sort.by("createdAt").descending())
            .page(Page.of(page, size))
            .list().stream()
            .map(ProductListDTO::from).toList();
    }

    // Invalidate toàn bộ cache
    @CacheInvalidateAll(cacheName = "product-list-cache")
    @Transactional
    public ProductDTO create(CreateProductRequest req) {
        // ... create product ...
    }
}

程式設計緩存

import io.quarkus.cache.Cache;
import io.quarkus.cache.CacheName;
import io.quarkus.cache.CaffeineCache;

@ApplicationScoped
public class CacheManager {

    @Inject
    @CacheName("product-cache")
    Cache productCache;

    public void warmUp() {
        // Pre-load popular products
        List<Product> popular = Product
            .find("status = 'ACTIVE'",
                  Sort.by("viewCount").descending())
            .page(Page.of(0, 100))
            .list();

        for (Product p : popular) {
            productCache.as(CaffeineCache.class)
                .put(p.id, CompletableFuture.completedFuture(
                    ProductDTO.from(p)));
        }
    }

    public void evictAll() {
        productCache.invalidateAll().await().indefinitely();
    }
}

健康檢查

依賴關係(自動可用)

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-smallrye-health</artifactId>
</dependency>

自動端點

# Tất cả health checks
curl http://localhost:8081/q/health

# Liveness — service đang chạy?
curl http://localhost:8081/q/health/live

# Readiness — service sẵn sàng nhận traffic?
curl http://localhost:8081/q/health/ready

# Startup — service đã start xong?
curl http://localhost:8081/q/health/started

內建健康檢查

Quarkus 自動新增:

  • 資料庫(資料來源):資料庫連線正常嗎?
  • Kafka:經紀人已連線?
  • Redis:快取已連線?

自訂健康檢查

import org.eclipse.microprofile.health.*;

@Liveness
@ApplicationScoped
public class ServiceLivenessCheck
        implements HealthCheck {

    @Override
    public HealthCheckResponse call() {
        return HealthCheckResponse
            .named("Product Service")
            .up()
            .withData("version", "1.0.0")
            .build();
    }
}

@Readiness
@ApplicationScoped
public class DatabaseReadinessCheck
        implements HealthCheck {

    @Inject
    ProductRepository productRepo;

    @Override
    public HealthCheckResponse call() {
        try {
            long count = productRepo.count();
            return HealthCheckResponse
                .named("Database")
                .up()
                .withData("products.count", count)
                .build();
        } catch (Exception e) {
            return HealthCheckResponse
                .named("Database")
                .down()
                .withData("error", e.getMessage())
                .build();
        }
    }
}

@Readiness
@ApplicationScoped
public class ExternalServiceCheck
        implements HealthCheck {

    @Inject @RestClient
    ProductServiceClient productClient;

    @Override
    public HealthCheckResponse call() {
        try {
            productClient.list(0, 1);
            return HealthCheckResponse
                .named("Product Service")
                .up().build();
        } catch (Exception e) {
            return HealthCheckResponse
                .named("Product Service")
                .down()
                .withData("error", e.getMessage())
                .build();
        }
    }
}

健康檢查回應

{
  "status": "UP",
  "checks": [
    {
      "name": "Product Service",
      "status": "UP",
      "data": { "version": "1.0.0" }
    },
    {
      "name": "Database",
      "status": "UP",
      "data": { "products.count": 150 }
    },
    {
      "name": "Reactive PostgreSQL connections health check",
      "status": "UP"
    }
  ]
}

API 閘道 — Nginx / Envoy

Nginx 配置

# nginx.conf
upstream product-service {
    server product-service:8080;
}

upstream order-service {
    server order-service:8080;
}

upstream payment-service {
    server payment-service:8080;
}

upstream keycloak {
    server keycloak:8080;
}

server {
    listen 80;
    server_name api.ecommerce.xdev.asia;

    # Rate limiting
    limit_req_zone $binary_remote_addr
        zone=api:10m rate=100r/s;

    # Product Service
    location /api/v1/products {
        limit_req zone=api burst=20 nodelay;
        proxy_pass http://product-service;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # Order Service
    location /api/v1/orders {
        limit_req zone=api burst=10 nodelay;
        proxy_pass http://order-service;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    # Payment Service
    location /api/v1/payments {
        limit_req zone=api burst=5 nodelay;
        proxy_pass http://payment-service;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    # Keycloak
    location /realms {
        proxy_pass http://keycloak;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    # Health check aggregation
    location /health {
        access_log off;
        default_type application/json;
        return 200 '{"status":"UP","gateway":"nginx"}';
    }
}

Docker 組合

services:
  api-gateway:
    image: nginx:1.25-alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf
    depends_on:
      - product-service
      - order-service
      - payment-service

練習

1.為產品服務添加Redis快取(getById, listByCategory) 2.建立/更新/刪除產品時實現快取失效 3. 建立自訂健康檢查:資料庫、外部服務 4.設定Nginx API網關路由到服務 5.在Nginx中加入速率限制 6. 測試:啟動→就緒→活性探針

總結

  • Redis 快取 (@CacheResult, @CacheInvalidate) 減少資料庫負載
  • 健康檢查 (/q/health/live, /q/health/ready) 對於 Kubernetes 探針
  • 自訂健康擴展 HealthCheck — 檢查資料庫、外部服務
  • API 閘道 (Nginx) — 單一入口點、路由、速率限制、TLS 終止
  • 速率限制保護後端服務免於濫用

下一篇文章:測試——@QuarkusTest 和 Testcontainers。