对于频繁访问且数据量不大的表,应使用缓存机制提高性能。
适合缓存的表特征:
缓存策略:
@Component
public class CacheService {
private static Map<Integer, DataType> cacheMap = new ConcurrentHashMap<>();
private static boolean isInitialized = false;
@Autowired
private RepositoryType repository;
@PostConstruct
public void initCache() {
loadDataToCache();
}
public synchronized void refreshCache() {
cacheMap.clear();
loadDataToCache();
}
private void loadDataToCache() {
List<DataType> dataList = repository.findAll();
cacheMap = dataList.stream()
.collect(Collectors.toConcurrentMap(DataType::getKeyField, Function.identity()));
isInitialized = true;
}
public DataType getByKey(Integer key) {
if (!isInitialized) {
synchronized (CacheService.class) {
if (!isInitialized) {
loadDataToCache();
}
}
}
return cacheMap.get(key);
}
}