缓存不可用时的数据库降级:本地开发设置

缓存不可用时的数据库降级:本地开发设置

本指南构建了一个本地 Spring Boot 3.2.6 服务,该服务在正常情况下从 Redis 读取监控摘要,并在 Redis 不可用时自动降级(fallback)到 PostgreSQL。这种降级机制被刻意地保护了起来,使用了较短的 Redis 超时时间、熔断器(Circuit Breaker)、最后已知有效的(last-known-good)本地缓存、Single-Flight(单次请求)协调、有界数据库并发、专用的降级连接池、查询超时以及明确的降级响应元数据。

Series: 安全运营平台 2026 (22 articles)

  1. …
  2. 13
    缓存不可用时的数据库降级:本地开发设置 This article
Dev @ Vertex Macro



安全运营平台

Project Summary(6W 路演框架)

  • Who(目标客户与核心角色):面向大型企业的安全运维团队,由 AI 全栈开发工程师主导核心架构与业务域研发。
  • What(核心产品与痛点解决):企业级一体化安全运营管理平台,解决海量安全告警处理滞后及风险管控分散的痛点,提供网络安全监测、资产管控、漏洞治理与 AI 智能分析一体化能力。
  • Why(核心壁垒与竞争优势):「定时任务 + Redis 缓存 + 未命中实时聚合回填」三层数据供给策略,将核心接口响应压至 50ms 以内;实现从风险识别到防护响应的全自动化闭环。
  • Where(应用场景与部署环境):覆盖企业多场景安全运维、防火墙设备联动及域名安全监测,支持基于 Docker 容器编排的多环境隔离部署与数据源动态切换。
  • When(时效性与实时能力):日均实时处理 10 万+ 条全网安全设备原始告警,支持 5 分钟级定时聚合与缓存刷新,150+ 表万级数据全表聚合任务耗时控制在 3 秒以内。
  • How(技术路径与交付机制):基于微服务架构拆分业务模块、复用公共能力库,构建「Kafka + InfluxDB + 规则引擎」实时分析与设备自动化联动链路。

Business

  • AI:对接 AI Agent 实现攻击路径智能研判、系统/资产/漏洞三维风险评级及自动化整改建议生成。
  • 自动化:通过 IP 黑名单 AI 分析公开接口支撑防火墙设备拉取数据,实现从风险识别到防护响应全程自动化。
  • 高并发:支撑 150+ 张业务表及日均 10 万+ 条告警数据实时处理,核心监测接口响应由 2 秒+ 优化至 50ms 以内,纯 Redis 读取接口 QPS 承载量达 500+。
  • 高可用:缓存失效自动降级查库,保障系统 99.9% 高可用性。
  • 信创:实现达梦数据库 与 PostgreSQL 无缝切换。
  • 提效:通过微服务独立迭代及公共能力库复用大幅提升研发与交付效率。

Tech Stack

  • 后端:Spring Boot 3.2.6
  • 前端:Vue3
  • 数据库:InfluxDB
  • 缓存:Redis
  • 中间件:Kafka,PostgreSQL
  • 容器化:Docker



第 11 步:添加定时刷新和受控预热

创建  src/main/java/com/example/fallback/service/SummaryRefreshScheduler.java :
package com.example.fallback.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SummaryRefreshScheduler {

private static final Logger log = LoggerFactory.getLogger(SummaryRefreshScheduler.class);

private final FallbackCoordinator coordinator;
private final List<String> tenants;

public SummaryRefreshScheduler(
FallbackCoordinator coordinator,
@Value("${app.scheduler.tenants}") List<String> tenants
) {
this.coordinator = coordinator;
this.tenants = List.copyOf(tenants);
}

@Scheduled(
initialDelayString = "10000",
fixedDelayString = "${app.scheduler.refresh-delay-ms}"
)
public void refresh() {
for (String tenantId : tenants) {
try {
coordinator.refresh(tenantId);
log.info("Refreshed summary for tenant {}", tenantId);
Thread.sleep(100);
} catch (Exception ex) {
log.warn("Refresh failed for tenant {}: {}", tenantId, ex.getMessage());
}
}
}
}
这里的 100 毫秒暂停是一个简单的本地预热控制。在更大型的实现中,应当使用有界执行器(Bounded Executor)、优先级队列以及随机抖动(Jitter),而不是同时刷新每个租户。

第 12 步:暴露 API 和降级错误

创建  src/main/java/com/example/fallback/controller/MonitoringController.java :
package com.example.fallback.controller;

import com.example.fallback.dto.MonitoringSummary;
import com.example.fallback.service.FallbackCoordinator;
import jakarta.validation.constraints.Pattern;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Validated
@RestController
@RequestMapping("/api/v1/tenants/{tenantId}/monitoring-summary")
public class MonitoringController {

private final FallbackCoordinator coordinator;

public MonitoringController(FallbackCoordinator coordinator) {
this.coordinator = coordinator;
}

@GetMapping
public MonitoringSummary get(
@PathVariable
@Pattern(regexp = "[a-zA-Z0-9-]{1,64}")
String tenantId
) {
return coordinator.get(tenantId);
}

@PostMapping("/refresh")
public MonitoringSummary refresh(@PathVariable String tenantId) {
return coordinator.refresh(tenantId);
}

@DeleteMapping("/redis")
public ResponseEntity<Void> evictRedis(@PathVariable String tenantId) {
coordinator.evictRedis(tenantId);
return ResponseEntity.noContent().build();
}

@DeleteMapping("/local")
public ResponseEntity<Void> clearLocal(@PathVariable String tenantId) {
coordinator.clearLocal(tenantId);
return ResponseEntity.noContent().build();
}
}
创建  src/main/java/com/example/fallback/controller/ApiExceptionHandler.java :
package com.example.fallback.controller;

import com.example.fallback.exception.FallbackBusyException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.Instant;
import java.util.Map;

@RestControllerAdvice
public class ApiExceptionHandler {

@ExceptionHandler(FallbackBusyException.class)
ResponseEntity<Map<String, Object>> fallbackBusy(FallbackBusyException ex) {
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
.header(HttpHeaders.RETRY_AFTER, "2")
.body(Map.of(
"code", "DATABASE_FALLBACK_BUSY",
"message", ex.getMessage(),
"timestamp", Instant.now().toString()
));
}
}
HTTP 503 传达了服务正在保护其受损依赖项的信息。 Retry-After: 2  告诉客户端不要立即重试。

第 13 步:构建并启动应用程序

构建项目:
mvn clean test
启动应用程序:
MAVEN_OPTS='-Xms512m -Xmx512m' mvn spring-boot:run
检查健康状况:
curl -s http://localhost:8080/actuator/health
等待至少 10 秒钟进行定时刷新。请求一个摘要数据:
curl -s http://localhost:8080/api/v1/tenants/tenant-a/monitoring-summary
正常的响应应该报告  deliverySource  为  REDIS , degraded  为  false ,且  ageSeconds  的值很小。
通过应用程序接口而非直接使用  redis-cli  命令在 Toxiproxy 下检查 Redis 键。键名如下:
monitoring:v1:tenant:tenant-a:summary:24h

第 14 步:在 Redis 可用时验证缓存未命中 (Cache Miss)

仅删除 Redis 中的值:
curl -i -X DELETE \
http://localhost:8080/api/v1/tenants/tenant-a/monitoring-summary/redis
目前暂时不要清除本地缓存。请求摘要:
curl -s http://localhost:8080/api/v1/tenants/tenant-a/monitoring-summary
响应应该报告  LOCAL_STALE 。此时 Redis 是可用的,但键不存在,所以服务重用了“最后已知有效”的本地缓存值,而不是执行另一次数据库查询。
强制执行一次完全冷启动未命中(同时清除 Redis 和本地缓存):
curl -s -X DELETE \
http://localhost:8080/api/v1/tenants/tenant-a/monitoring-summary/redis

curl -s -X DELETE \
http://localhost:8080/api/v1/tenants/tenant-a/monitoring-summary/local
再次请求摘要:
curl -s http://localhost:8080/api/v1/tenants/tenant-a/monitoring-summary
响应应该报告  DATABASE_FALLBACK 。结果会被写回到 Redis 和 Caffeine 中。下一次请求应该返回  REDIS 。

第 15 步:模拟 Redis 延迟

通过 Toxiproxy 添加 500 毫秒的延迟:
curl -s -X POST \
http://localhost:8474/proxies/redis/toxics \
-H 'Content-Type: application/json' \
-d '{
"name": "redis_latency",
"type": "latency",
"stream": "downstream",
"toxicity": 1.0,
"attributes": {
"latency": 500,
"jitter": 25
}
}'
发送多个请求:
for i in $(seq 1 10); do
curl -s -o /dev/null -w '%{http_code} %{time_total}\n' \
http://localhost:8080/api/v1/tenants/tenant-a/monitoring-summary
done
Redis 的命令超时时间为 250 毫秒。在发生足够多的慢调用之后,熔断器应该会打开,随后的请求将跳过 Redis。由于本地缓存包含了最后一次成功的值,响应应当使用  LOCAL_STALE  而非 PostgreSQL 查询。
检查熔断器健康状况:
curl -s http://localhost:8080/actuator/health
检查熔断器事件:
curl -s http://localhost:8080/actuator/circuitbreakerevents
移除延迟注入配置 (toxic):
curl -s -X DELETE \
http://localhost:8474/proxies/redis/toxics/redis_latency
等待至少 10 秒(让处于打开状态的时间段过去),然后发出两个或多个请求,使得半开(Half-Open)探测能够验证 Redis 的恢复情况。

第 16 步:模拟完整的 Redis 连接失败

禁用 Toxiproxy 代理:
curl -s -X POST http://localhost:8474/proxies/redis \
-H 'Content-Type: application/json' \
-d '{
"name": "redis",
"listen": "0.0.0.0:6380",
"upstream": "redis:6379",
"enabled": false
}'
请求已预热的租户:
curl -s http://localhost:8080/api/v1/tenants/tenant-a/monitoring-summary
预期的交付来源(delivery source)是  LOCAL_STALE ,因为进程内缓存包含有效的最近已知结果。
在 Redis 仍不可用时清除本地缓存:
curl -s -X DELETE \
http://localhost:8080/api/v1/tenants/tenant-a/monitoring-summary/local
再次请求摘要:
curl -s http://localhost:8080/api/v1/tenants/tenant-a/monitoring-summary
预期的交付来源是  DATABASE_FALLBACK 。该服务无法对 Redis 进行数据回填,但会将结果存储在 Caffeine 中。随后的请求应使用  LOCAL_STALE 。
重新启用代理:
curl -s -X POST http://localhost:8474/proxies/redis \
-H 'Content-Type: application/json' \
-d '{
"name": "redis",
"listen": "0.0.0.0:6380",
"upstream": "redis:6379",
"enabled": true
}'
等待熔断器过渡到半开(Half-Open)状态。持续请求该摘要直至熔断器关闭。运行手动刷新以重新预热 Redis:
curl -s -X POST \
http://localhost:8080/api/v1/tenants/tenant-a/monitoring-summary/refresh

第 17 步:验证 Single-Flight(单飞)降级

再次禁用 Redis。清除一个新租户键的本地缓存值:
curl -s -X POST http://localhost:8474/proxies/redis \
-H 'Content-Type: application/json' \
-d '{
"name": "redis",
"listen": "0.0.0.0:6380",
"upstream": "redis:6379",
"enabled": false
}'
针对同一个冷键 (cold key) 发送 20 个并发请求:
seq 1 20 | xargs -n1 -P20 -I{} \
curl -s http://localhost:8080/api/v1/tenants/cold-tenant/monitoring-summary
其中一个请求应执行 PostgreSQL 聚合查询。在首次查询完成之后,等待中的其他请求应当重用该本地值。这保护了数据库,避免在一个应用程序进程内收到 20 个针对同一个冷键的重复紧急查询。
检查数据库交付指标:
curl -s 'http://localhost:8080/actuator/metrics/fallback.delivery?tag=source:database'
在正常的本地计时下,共享冷键的数据库交付计数器应只增加 1 次。

第 18 步:验证数据库隔离舱 (Bulkhead)

保持 Redis 处于禁用状态。生成针对许多唯一冷租户键的请求,这样 Single-Flight 机制就无法将它们合并:
seq 1 50 | xargs -n1 -P50 -I{} \
curl -s -o /dev/null -w '%{http_code}\n' \
http://localhost:8080/api/v1/tenants/cold-{}/monitoring-summary
一次最多只能运行 8 个数据库降级查询。未能在 100 毫秒内获得许可的请求将收到 HTTP 503 以及  DATABASE_FALLBACK_BUSY  和  Retry-After: 2  响应。
检查各项指标:
curl -s http://localhost:8080/actuator/metrics/fallback.permits.available
curl -s 'http://localhost:8080/actuator/metrics/fallback.delivery?tag=source:rejected'
curl -s http://localhost:8080/actuator/metrics/hikaricp.connections.pending
其核心行为是有界限的压力控制。该服务会在超出的读取请求消耗掉每个数据库连接和请求线程之前主动拒绝它们。

第 19 步:运行开发环境的缓存故障负载测试

创建  load-test/cache_failure.js :
import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = {
scenarios: {
degraded_reads: {
executor: 'constant-arrival-rate',
rate: 100,
timeUnit: '1s',
duration: '60s',
preAllocatedVUs: 50,
maxVUs: 200,
},
},
thresholds: {
http_req_failed: ['rate<0.05'],
checks: ['rate>0.95'],
},
};

export default function () {
const response = http.get(
'http://localhost:8080/api/v1/tenants/tenant-a/monitoring-summary'
);

check(response, {
'status is 200 or protected 503': (r) =>
r.status === 200 || r.status === 503,
'degraded response identifies its source': (r) => {
if (r.status === 503) return true;
try {
const body = JSON.parse(r.body);
return ['LOCAL_STALE', 'LOCAL_AFTER_WAIT', 'DATABASE_FALLBACK']
.includes(body.deliverySource);
} catch (e) {
return false;
}
},
});

sleep(0.01);
}
首先预热 tenant-a,然后禁用 Redis 并运行测试:
k6 run load-test/cache_failure.js
因为 tenant-a 有一个“最后已知有效”的值,大多数请求应当返回  LOCAL_STALE 。该测试证明了平台能够在缓存停机期间避免将 100 QPS 的流量转移给 PostgreSQL。
如需进行冷键过载测试,请使用唯一的租户名称,并期望在降级隔离舱满载时产生受控的 HTTP 503 响应。不要将这些响应解读为缺陷,它们正是依赖项保护机制在开发场景中的实际体现。

第 20 步:观察降级路径

检查所有交付来源计数器:
curl -s http://localhost:8080/actuator/metrics/fallback.delivery
检查 Redis 指标:
curl -s http://localhost:8080/actuator/metrics/fallback.redis.hit
curl -s http://localhost:8080/actuator/metrics/fallback.redis.miss
检查 HTTP 百分位数及计数:
curl -s http://localhost:8080/actuator/metrics/http.server.requests
检查 Prometheus 输出:
curl -s http://localhost:8080/actuator/prometheus | \
grep -E 'fallback_|resilience4j_circuitbreaker|hikaricp|http_server_requests'
有用的本地观测数据包括:熔断器打开的时间、本地过期 (stale) 响应的比例、数据库降级查询的次数、被拒绝请求的数量、降级连接池的使用情况以及响应的过期年龄。

第 21 步:验证查询超时行为

临时在  application.yml  中缩短查询超时时间:
app:
fallback:
query-timeout-ms: 1
重启应用程序,禁用 Redis,清空本地缓存,然后请求一个冷键。PostgreSQL 应该会很快取消该聚合查询。在观察到这一行为后,请将该值恢复至 800 毫秒。
目的是确认失败的客户端请求不会导致昂贵的查询无限期地运行。确切的超时时间必须长于正常的查询延迟,但要短于该端点的最大降级响应预算时间。

第 22 步:恢复后逐步预热 Redis

通过 Toxiproxy 重新启用 Redis。允许熔断器的 10 秒开启状态过期。发送少量请求,以便那两次半开状态调用能够验证 Redis 的健康状况。
首先刷新高价值的租户:
curl -s -X POST \
http://localhost:8080/api/v1/tenants/tenant-a/monitoring-summary/refresh

sleep 1

curl -s -X POST \
http://localhost:8080/api/v1/tenants/tenant-b/monitoring-summary/refresh
不要一次性发出数千个刷新请求。故障发生后,大规模的冷缓存预热可能会立即使 PostgreSQL 过载。调度程序中那一小段暂停时间演示了本地的受控预热方式。
在恢复过渡期间保留 Caffeine 缓存值。如果在恢复期间 Redis 再次变得不稳定,它们可以提供业务的连续性。

第 23 步:添加针对性的开发测试

创建  src/test/java/com/example/fallback/service/MonitoringSummaryTest.java :
package com.example.fallback.service;

import com.example.fallback.dto.MonitoringSummary;
import org.junit.jupiter.api.Test;

import java.time.Instant;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;

class MonitoringSummaryTest {

@Test
void marksLastKnownValueAsDegraded() {
Instant generatedAt = Instant.parse("2026-11-19T10:00:00Z");
MonitoringSummary original = new MonitoringSummary(
"tenant-a",
Instant.parse("2026-11-18T10:00:00Z"),
generatedAt,
generatedAt,
100,
80,
Map.of("CRITICAL", 5L, "HIGH", 20L),
"REDIS",
false,
0,
1
);

MonitoringSummary degraded = original.deliveredAs(
"LOCAL_STALE",
true,
Instant.parse("2026-11-19T10:05:00Z")
);

assertThat(degraded.deliverySource()).isEqualTo("LOCAL_STALE");
assertThat(degraded.degraded()).isTrue();
assertThat(degraded.ageSeconds()).isEqualTo(300);
assertThat(degraded.totalAlerts()).isEqualTo(100);
}
}
运行测试:
mvn test
这些测试是本地开发测试,它们并非生产验收测试。

第 24 步:调整本地降级策略

仅当业务线能够安全地消费较旧的数据时,才增加  local-hard-age (本地强制过期时间)。较长的时间值可提升连续性,但也增加了基于陈旧信息采取行动的风险。
保持足够短的 Redis 超时时间,以保留总请求耗时预算。如果正常的本地 p99 Redis 延迟低于 10 毫秒,那么 250 毫秒的超时就留出了可观的故障检测余地。在进一步缩短该时间前,请进行测量。
不要将降级信号量(Semaphore)的值设置得高于专属降级连接池大小。示例中使用了 8 个许可和 8 个降级连接,这样应用程序就不会在 HikariCP 内部创建一个隐藏的等待队列。
保持较短的许可等待时间(permit wait)。100 毫秒的等待时间允许短暂的资源竞争,同时又避免了成百上千个请求线程等待数据库容量。
使用紧凑的紧急查询。如果常规监控仪表板会连接诸多业务域,则其数据库降级路径应仅返回安全关键字段。
若要在本地试验多实例场景,可以在另一个端口上运行第二个应用程序实例。请记住,Caffeine 和 Single-Flight 锁是进程本地的。数据库降级并发额度必须将所有实例作为一个整体来统筹考量。

第 25 步:重置本地环境

如果 Redis 代理被禁用了,请重新启用它:
curl -s -X POST http://localhost:8474/proxies/redis \
-H 'Content-Type: application/json' \
-d '{
"name": "redis",
"listen": "0.0.0.0:6380",
"upstream": "redis:6379",
"enabled": true
}'
移除所有的 Toxiproxy 注入异常(toxics):
curl -s http://localhost:8474/proxies/redis/toxics | \
grep -o '"name":"[^"]*"' | \
cut -d '"' -f 4 | \
while read -r toxic; do
curl -s -X DELETE \
"http://localhost:8474/proxies/redis/toxics/${toxic}"
done
通过  Ctrl+C  停止 Spring Boot 应用程序。
停止容器同时保留数据:
docker compose stop
移除容器,同时保留命名卷(named volumes):
docker compose down
移除容器及所有的本地数据:
docker compose down -v
清除 Maven 的构建输出:
mvn clean
这个完整的本地实现展示了安全的自动数据库降级方案,而不是无条件重定向流量。Redis 依然保持为常态的低延迟路径。Resilience4j 会检测命令故障并打开熔断器。Caffeine 保存了有界限的“最后已知有效”结果。Single-Flight(单飞)协调可防止为同一个键执行重复的紧急工作。信号量(Semaphore)以及专用的 HikariCP 连接池限制了数据库压力。PostgreSQL 语句级别超时可取消超预算的查询。当降级容量被耗尽时,HTTP 503 和  Retry-After  能够保护整个系统。Toxiproxy 则提供了一种无需更改应用程序代码即可测试延迟、中断及恢复情况的可重复方法。

Series: 安全运营平台 2026 (22 articles)

  1. …
  2. 13
    缓存不可用时的数据库降级:本地开发设置 This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article