
在许多业务场景中,我们经常需要根据一组id查询批量数据。例如,查询一批学生信息:
public class Student {
private int id;
private String name;
// Getters and Setters
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override
public String toString() {
return "Student{" + "id=" + id + ", name='" + name + '\'' + '}';
}
}对应的数据库查询通常是:
SELECT name FROM Student WHERE id IN (:ids);
我们期望的理想缓存行为是: 当请求一组学生ID(例如 [2, 3, 4, 5, 6])时,系统首先检查缓存。如果 [2, 4, 6] 的数据已在缓存中,则直接从缓存获取;对于 [3, 5] 这些缓存中不存在的ID,则只针对它们发起数据库查询。查询到 [3, 5] 的数据后,将其存入缓存,并将所有数据合并返回。这种“部分缓存命中,部分数据库查询”的策略可以显著提高数据检索效率,减少数据库负载。
Spring Framework 提供的缓存抽象(Spring Cache Abstraction)通过 @Cacheable 等注解,简化了缓存逻辑的集成。然而,对于上述批量查询的特定需求,其默认行为存在一些局限性。
Spring 的 @Cacheable 注解通常应用于方法级别,其工作机制类似于 Map.computeIfAbsent(KEY, Function<KEY, VALUE>)。这意味着:
例如,一个使用 @Cacheable 的服务方法可能如下:
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Set;
@Service
public class StudentService {
// 假设这是与数据库交互的Repository
private StudentRepository studentRepository;
public StudentService(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
@Cacheable(value = "students")
public List<Student> findStudentsByIds(Set<Integer> ids) {
System.out.println("从数据库查询学生信息,IDs: " + ids);
return studentRepository.findByIdIn(ids);
}
}在这种情况下,如果 findStudentsByIds 方法的缓存键(由 ids 参数生成)在缓存中,那么即使 ids 集合中的部分学生数据已过期或更新,整个方法也不会被执行,导致返回旧数据。反之,如果缓存键不存在,则整个 ids 集合都会被用于数据库查询,无法利用缓存中已有的部分数据。
默认情况下,Spring Cache Abstraction 使用方法的所有参数来生成缓存键。对于 findStudentsByIds(Set<Integer> ids) 方法,缓存键将是整个 Set<Integer> 对象,而缓存值是 List<Student>。
缓存键 (Set<Integer>) | 缓存值 (List<Student>)
----------------------|-----------------------
{1, 2, 3} | [Student(id=1), Student(id=2), Student(id=3)]
{4, 5} | [Student(id=4), Student(id=5)]这与我们期望的“按单个学生ID缓存”的粒度不符。我们通常希望每个 Student 对象都以其 id 作为键单独缓存:
缓存键 (Integer) | 缓存值 (Student) -----------------|----------------- 1 | Student(id=1, name='Jon Doe') 2 | Student(id=2, name='Jane Doe') 3 | Student(id=3, name='Pie Doe')
虽然可以通过自定义键生成策略来改变缓存键,但这并不能直接解决“部分缓存命中”的问题,因为 @Cacheable 仍然是针对整个方法调用进行缓存判断。
Spring 的 org.springframework.cache.Cache 接口提供了 get(Object key) 方法来获取单个缓存项。如果我们需要手动检查一组ID是否在缓存中,就需要对每个ID调用一次 get() 方法。当请求的ID数量很大时(例如1000个ID),频繁的单键访问可能会带来显著的性能开销,尤其是在分布式缓存环境中。
鉴于 Spring Cache Abstraction 的默认局限性,我们需要通过手动管理缓存和数据库交互来实现所需的策略。以下是一个详细的实现方案:
核心思路是:
以下是实现此逻辑的代码示例:
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class OptimizedStudentService {
private final StudentRepository studentRepository;
private final Cache studentsCache; // 直接引用Cache实例
public OptimizedStudentService(StudentRepository studentRepository, CacheManager cacheManager) {
this.studentRepository = studentRepository;
// 获取名为 "students" 的缓存实例
this.studentsCache = cacheManager.getCache("students");
if (this.studentsCache == null) {
throw new IllegalStateException("Cache 'students' not found. Please configure it.");
}
}
/**
* 根据一组ID查询学生信息,优先从缓存获取,缺失部分从数据库查询。
*
* @param studentIds 需要查询的学生ID集合
* @return 匹配的学生列表
*/
public List<Student> findStudentsWithPartialCache(Set<Integer> studentIds) {
List<Student> result = new ArrayList<>();
Set<Integer> idsToQueryDb = new HashSet<>(studentIds); // 初始所有ID都需要查询
// 步骤 1: 尝试从缓存中获取数据
// 注意:这里是单键循环访问缓存,可能存在性能瓶颈,见后续优化章节
for (Integer id : studentIds) {
Cache.ValueWrapper valueWrapper = studentsCache.get(id);
if (valueWrapper != null) {
Object cachedObject = valueWrapper.get();
if (cachedObject instanceof Student) {
Student student = (Student) cachedObject;
result.add(student);
idsToQueryDb.remove(id); // 从待查询数据库的ID集合中移除已缓存的ID
}
}
}
// 步骤 2: 识别出需要从数据库查询的缺失ID
// idsToQueryDb 现在包含了所有缓存中未找到的ID
// 步骤 3: 针对缺失的ID发起数据库查询
if (!idsToQueryDb.isEmpty()) {
System.out.println("从数据库查询缺失学生信息,IDs: " + idsToQueryDb);
List<Student> dbStudents = studentRepository.findByIdIn(idsToQueryDb);
// 步骤 4: 将数据库查询结果存入缓存
for (Student student : dbStudents) {
studentsCache.put(student.getId(), student);
result.add(student); // 将新查询到的数据也添加到结果集
}
}
// 步骤 5: 合并并返回所有数据
// 确保返回的列表是去重且包含所有请求ID的数据(如果存在)
// 实际场景可能需要根据业务逻辑对结果进行排序或进一步处理
return result.stream()
.distinct() // 去重,以防万一
.collect(Collectors.toList());
}
}注意事项:
上述手动方案中,通过循环调用 studentsCache.get(id) 来检查每个ID的缓存状态,这在ID数量巨大时可能效率低下。理想情况下,缓存提供商通常支持批量获取(multi-get)操作。
Spring 的 Cache 接口本身没有提供批量获取的方法,但它提供了一个 getNativeCache() 方法,允许我们访问底层缓存提供商(如 Ehcache, Caffeine, Hazelcast, Redis 等)的原生缓存对象。如果底层缓存支持批量获取,我们可以利用 getNativeCache() 进行优化。
例如,如果使用 Hazelcast 作为缓存提供商,其 IMap 接口提供了 getAll(Set<K> keys) 方法:
import com.hazelcast.map.IMap;
// ... 其他导入
@Service
public class OptimizedStudentService {
// ... 构造函数不变
public List<Student> findStudentsWithPartialCacheOptimized(Set<Integer> studentIds) {
List<Student> result = new ArrayList<>();
Set<Integer> idsToQueryDb = new HashSet<>(studentIds);
// 尝试获取原生缓存对象
Object nativeCache = studentsCache.getNativeCache();
if (nativeCache instanceof IMap) { // 如果是Hazelcast IMap
IMap<Integer, Student> hazelcastMap = (IMap<Integer, Student>) nativeCache;
// 批量从Hazelcast缓存获取数据
Map<Integer, Student> cachedStudentsMap = hazelcastMap.getAll(studentIds);
for (Map.Entry<Integer, Student> entry : cachedStudentsMap.entrySet()) {
result.add(entry.getValue());
idsToQueryDb.remove(entry.getKey()); // 移除已缓存的ID
}
} else {
// 如果不是IMap,或者不确定原生缓存类型,退回到单键循环访问
for (Integer id : studentIds) {
Cache.ValueWrapper valueWrapper = studentsCache.get(id);
if (valueWrapper != null && valueWrapper.get() instanceof Student) {
Student student = (Student) valueWrapper.get();
result.add(student);
idsToQueryDb.remove(id);
}
}
}
// ... 后续数据库查询和缓存更新逻辑与之前相同
if (!idsToQueryDb.isEmpty()) {
System.out.println("从数据库查询缺失学生信息 (优化版),IDs: " + idsToQueryDb);
List<Student> dbStudents = studentRepository.findByIdIn(idsToQueryDb);
for (Student student : dbStudents) {
studentsCache.put(student.getId(), student);
result.add(student);
}
}
return result.stream().distinct().collect(Collectors.toList());
}
}使用 getNativeCache() 的权衡:
Spring Cache Abstraction 旨在提供一个通用的缓存接口,以简化常见缓存模式的实现。然而,对于“批量查询中部分缓存命中,部分数据库查询”这种高级且精细的控制需求,其默认的声明式缓存机制(如 @Cacheable)并不能直接满足。
为了实现这种优化策略,我们需要:
最终选择哪种实现方式,应根据应用程序的具体性能要求、缓存提供商的选择以及对代码耦合度的容忍程度来决定。在许多情况下,手动管理缓存的复杂性是值得的,因为它能带来显著的性能提升和资源节约。
以上就是Spring Boot 缓存高级实践:优化批量数据查询的缓存与数据库协同机制的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号