架构与系统设计 / 系统课时
Redis 应该直接写进领域层吗
Redis 应该直接写进领域层吗
这节要解决的是依赖边界,而不是 Redis 能不能用。缓存可以显著降低读压力,但如果领域对象直接调用 Redis 客户端,业务规则就会依赖具体中间件。更稳妥的做法是让领域层表达业务语义,把缓存命中、TTL 与失效策略留在应用层或基础设施层。
学习目标
- 判断 Redis 依赖为什么通常不应进入领域模型
- 把缓存策略放到应用边界或基础设施适配器中
- 识别缓存失效与领域规则之间的边界
问题不在 Redis,而在依赖方向
领域层应该能够在没有 Redis 进程、连接池和序列化配置的情况下表达并测试业务规则。如果实体或领域服务直接注入 RedisTemplate、Redis 客户端或缓存 Key 规则,领域代码就开始承担基础设施职责。
真正属于领域的通常是“数据在多长时间后不再具有业务效力”“某个状态变更后旧快照不可继续使用”这类语义;至于是否使用 Redis、Key 怎么命名、TTL 怎么写入,则是技术策略。

把缓存放在应用边界
查询场景常用 Cache-Aside:应用服务先查缓存,未命中再读取 Repository,并把适合展示的读模型写回缓存。领域对象本身不需要知道这个过程。
下面是片段示例,ProductCache 是应用边界,RedisProductCache 位于基础设施层;示例依赖已配置的 Spring Data Redis 与 Jackson。
import java.math.BigDecimal;
import java.time.Duration;
import java.util.Optional;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
record ProductId(long value) {}
record Product(ProductId id, String name, BigDecimal price) {}
interface ProductRepository {
Optional<Product> findById(ProductId id);
}
record ProductView(long id, String name, BigDecimal price) {}
interface ProductCache {
Optional<ProductView> get(ProductId id);
void put(ProductView view, Duration ttl);
void evict(ProductId id);
}
final class ProductQueryService {
private static final Duration CACHE_TTL = Duration.ofMinutes(10);
private final ProductRepository repository;
private final ProductCache cache;
ProductQueryService(ProductRepository repository, ProductCache cache) {
this.repository = repository;
this.cache = cache;
}
ProductView query(ProductId id) {
return cache.get(id).orElseGet(() -> {
Product product = repository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("product not found"));
ProductView view =
new ProductView(product.id().value(), product.name(), product.price());
cache.put(view, CACHE_TTL);
return view;
});
}
}
@Component
final class RedisProductCache implements ProductCache {
private final StringRedisTemplate redis;
private final ObjectMapper objectMapper;
RedisProductCache(StringRedisTemplate redis, ObjectMapper objectMapper) {
this.redis = redis;
this.objectMapper = objectMapper;
}
@Override
public Optional<ProductView> get(ProductId id) {
String json = redis.opsForValue().get(key(id));
if (json == null) {
return Optional.empty();
}
try {
return Optional.of(objectMapper.readValue(json, ProductView.class));
} catch (JsonProcessingException e) {
throw new IllegalStateException("invalid cached product", e);
}
}
@Override
public void put(ProductView view, Duration ttl) {
try {
redis.opsForValue().set(
key(new ProductId(view.id())),
objectMapper.writeValueAsString(view),
ttl
);
} catch (JsonProcessingException e) {
throw new IllegalStateException("cannot serialize product", e);
}
}
@Override
public void evict(ProductId id) {
redis.delete(key(id));
}
private String key(ProductId id) {
return "product:view:" + id.value();
}
}预期结果:在已有 Spring 容器、Redis 连接与 Jackson 配置的项目中,首次查询缓存未命中时读取 Repository 并回填 Redis;后续查询命中缓存后直接返回 ProductView,整个过程中领域对象没有依赖 Redis API。这段代码依赖项目运行环境,因此属于片段示例。
更新路径先解决失效问题
缓存最危险的地方通常不是“读不到”,而是“读到旧值”。当商品名称或价格更新成功后,应用层需要在合适的事务时机删除或更新对应缓存。若数据库提交成功而缓存失效失败,就可能短时间返回旧数据。
因此,写模型不要简单依赖“先改 Redis、再改数据库”来保证一致性。常见做法是数据库作为事实来源,提交成功后再失效缓存,并结合较短 TTL、重试或可靠事件降低失效失败的影响。对一致性要求很高的业务,还需要单独设计同步机制,而不是把 Redis 调用塞进实体方法。
领域可以表达时效,但不表达 Redis
如果“报价只在五分钟内有效”本身就是业务规则,那么五分钟是领域语义,可以出现在值对象或策略中;但 EXPIRE 命令、Key 前缀和序列化格式仍然属于基础设施细节。
判断边界是否合理时,可以问一句:把 Redis 换成 Caffeine、Memcached 或完全关闭缓存后,领域规则是否仍能原样成立?如果答案是肯定的,缓存通常就放在了正确的位置。