Spring Boot项目中如何调用其他类预加载到缓存中的数据?
Spring Boot 启动预加载缓存的调用方案
方案1:直接注入CacheManager操作缓存
这是最通用的方式,适用于所有场景,既可以根据id取单条,也可以获取缓存内全量数据。
代码示例
import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentMap; import java.util.stream.Collectors; @Service public class ItemTypeService { @Autowired private CacheManager cacheManager; // 根据itemTypeId获取单个类型数据 public ColtemType getTypeById(Integer itemTypeId) { Cache typeCache = cacheManager.getCache("types"); if (typeCache == null) { return null; } Cache.ValueWrapper wrapper = typeCache.get(itemTypeId); return wrapper != null ? (ColtemType) wrapper.get() : null; } // 获取缓存中所有类型数据 public List<ColtemType> getAllCachedTypes() { Cache typeCache = cacheManager.getCache("types"); if (typeCache == null) { return Collections.emptyList(); } // 你使用的是ConcurrentMapCacheManager,底层存储是ConcurrentMap Object nativeCache = typeCache.getNativeCache(); if (nativeCache instanceof ConcurrentMap) { ConcurrentMap<?, ?> cacheMap = (ConcurrentMap<?, ?>) nativeCache; return cacheMap.values().stream() .filter(ColtemType.class::isInstance) .map(ColtemType.class::cast) .collect(Collectors.toList()); } return Collections.emptyList(); } }
方案2:使用Spring Cache注解简化操作
如果只需要根据id查询单条数据,用@Cacheable注解更简洁,不需要手动操作CacheManager。
代码示例
import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class ItemTypeService { @Autowired private ItemType itemType; // 缓存名对应你预定义的types,key为传入的itemTypeId @Cacheable(value = "types", key = "#itemTypeId") public ColtemType getTypeById(Integer itemTypeId) { // 正常启动时已经预加载了所有数据,不会走到方法内的查询逻辑,这里可以加数据库查询作为兜底 return itemType.findById(itemTypeId).orElse(null); } }
注意事项
- 调用缓存的类必须是Spring托管的Bean,需要加上
@Service/@Component/@RestController等注解,否则无法注入依赖,缓存注解也不会生效 - 如果后续需要更新缓存,可以手动调用CacheManager的
put/evict方法,也可以用@CachePut/@CacheEvict注解操作
内容的提问来源于stack exchange,提问作者Jhon
相关产品推荐
相关产品推荐

