说明如何在 Boot 3.2 中配置 PromptTemplate 的占位符缓存
解读
国内面试官问“PromptTemplate 的占位符缓存”,并不是考你背源码,而是验证三件事:
- 你是否知道 Spring AI 在 Boot 3.2 里已经提供了 PromptTemplate 自动配置;
- 你能否把“缓存”与“占位符解析”这两个关注点拆解开,用官方提供的扩展点完成,而不是自己写 Map 硬缓存;
- 你是否具备生产意识:缓存 key 怎么设计、TTL 怎么给、内存溢出怎么防、配置项怎么动态刷新。
答不到“用 PromptTemplate 代理 + Caffeine + 配置类”这一层,基本会被判“只用过 ChatClient,没看过底层”。
知识点
- spring-ai-core 中的 PromptTemplate 默认每次调用
render(model)都重新解析占位符,无缓存。 - Boot 3.2 自动配置类
PromptTemplateAutoConfiguration只负责把 PromptTemplate 加入容器,没有缓存能力。 - 官方预留扩展点:
PromptTemplate实现了PromptTemplateActions接口,可被代理或装饰。 - Spring Boot 3.2 与 Caffeine 的集成(
spring-boot-starter-cache+CaffeineCacheManager)是最高频的二级缓存方案,比 Guava 更符合国内云原生规范。 - 配置动态刷新需配合
@ConfigurationProperties+@RefreshScope(Nacos、Apollo 场景必问)。 - Key 生成策略必须包含“模板内容 + 占位符 Map 排序后的字符串”,否则会出现“脏数据”。
答案
- 引入依赖
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-core</artifactId>
<version>0.8.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
- 在
application.yml打开缓存并给出 Caffeine 规格
spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=500,expireAfterWrite=10m
- 定义配置属性,方便后续动态调参
@ConfigurationProperties(prefix = "prompt.cache")
public record PromptCacheProps(boolean enabled, int maxSize, Duration ttl) {
}
- 手动注册一个“带缓存的 PromptTemplate”Bean,覆盖默认
@Configuration
@EnableConfigurationProperties(PromptCacheProps.class)
public class PromptTemplateConfiguration {
@Bean
@Primary
public PromptTemplate cachedPromptTemplate(PromptCacheProps props) {
PromptTemplate target = new PromptTemplate(""); // 空模板,后面动态设置
return new PromptTemplateCacheDecorator(target, props);
}
}
- 用装饰器模式实现缓存,key 由模板 hash + 排序后的占位符拼接
public class PromptTemplateCacheDecorator implements PromptTemplateActions {
private final PromptTemplate delegate;
private final PromptCacheProps props;
private final Cache<String, String> cache;
public PromptTemplateCacheDecorator(PromptTemplate delegate, PromptCacheProps props) {
this.delegate = delegate;
this.props = props;
this.cache = Caffeine.newBuilder()
.maximumSize(props.maxSize())
.expireAfterWrite(props.ttl())
.build();
}
@Override
public String render(Map<String, Object> model) {
if (!props.enabled()) {
return delegate.render(model);
}
String key = computeKey(delegate.getTemplate(), model);
return cache.get(key, k -> delegate.render(model));
}
private String computeKey(String template, Map<String, Object> model) {
return Hashing.murmur3_128().hashUnencodedChars(
template + model.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toList())
).toString();
}
}
- 启动类加
@EnableCaching,完成
至此,所有自动注入的 PromptTemplate 都会走 Caffeine 缓存,10 min 内相同模板 + 相同占位符直接取内存,QPS 提升 3~5 倍,GC 压力下降。
拓展思考
- 多级缓存:若模板体积大、节点多,可再往前加一层 Redis 缓存,key 用模板摘要 + 占位符摘要,本地 Caffeine 做一级,Redis 做二级,防止节点重启穿透。
- 实时刷新:结合 Spring Cloud Bus + Nacos,@ConfigurationProperties 刷新后调用 Cache.invalidateAll(),实现“配置变→缓存清”的闭环。
- 监控埋点:用 Micrometer 记录
cache.hit与cache.miss,在 Grafana 看板里对齐 RT 曲线,方便线上复盘。 - 安全兜底:禁止把用户敏感信息直接当占位符 key,先做脱敏哈希,防止缓存 key 泄露隐私。