Spring boot应用程序启动时如何缓存数据

我有一个连接到 SQL Server 数据库的 Spring boot 应用程序。我需要一些帮助来在我的应用程序中使用缓存。我有一个 CodeCategory 表,其中包含许多代码的代码列表。该表将每月加载一次,数据每月仅更改一次。我想在应用程序启动时缓存整个表。在对表的任何后续调用中,都应从此缓存中获取值,而不是调用数据库。

例如,

List<CodeCategory> findAll();

我想在应用程序启动期间缓存上面的数据库查询值。如果有像这样的数据库调用,List<CodeCategory> findByCodeValue(String code)应该从已经缓存的数据中获取代码结果,而不是调用数据库。

请让我知道如何使用 spring boot 和 ehcache 来实现这一点。


吃鸡游戏
浏览 225回答 4
4回答

摇曳的蔷薇

正如所指出的,设置 ehcache 需要一些时间,并且不能完全与@PostConstruct. 在这种情况下,使用ApplicationStartedEvent加载缓存。GitHub 仓库:spring-ehcache-demo@Serviceclass CodeCategoryService{&nbsp; &nbsp;@EventListener(classes = ApplicationStartedEvent.class )&nbsp; &nbsp;public void listenToStart(ApplicationStartedEvent event) {&nbsp; &nbsp; &nbsp; &nbsp; this.repo.findByCodeValue("100");&nbsp; &nbsp;}}interface CodeCategoryRepository extends JpaRepository<CodeCategory, Long>{&nbsp; &nbsp; @Cacheable(value = "codeValues")&nbsp; &nbsp; List<CodeCategory> findByCodeValue(String code);}注意:其他人指出的方法有多种。您可以根据自己的需要进行选择。

繁星coding

我的方法是定义一个通用的缓存处理程序@FunctionalInterfacepublic interface GenericCacheHandler {List<CodeCategory> findAll();&nbsp;}及其实现如下@Component@EnableScheduling&nbsp; // Importantpublic class GenericCacheHandlerImpl implements GenericCacheHandler {@Autowiredprivate CodeRepository codeRepo;private List<CodeCategory> codes = new ArrayList<>();@PostConstructprivate void intializeBudgetState() {&nbsp; &nbsp; List<CodeCategory> codeList = codeRepo.findAll();&nbsp; &nbsp; // Any customization goes here&nbsp; &nbsp; codes = codeList;}@Overridepublic List<CodeCategory> getCodes() {&nbsp; &nbsp; return codes;}}在服务层调用如下@Servicepublic class CodeServiceImpl implements CodeService {@Autowiredprivate GenericCacheHandler genericCacheHandler;@Overridepublic CodeDTO anyMethod() {&nbsp; &nbsp; return genericCacheHandler.getCodes();}&nbsp; &nbsp;}

翻过高山走不出你

使用CommandLineRunner接口。基本上,您可以创建一个 Spring @Component 并实现 CommandLineRunner 接口。您将不得不重写它的运行方法。run 方法将在应用程序启动时调用。@Componentpublic class DatabaseLoader implements&nbsp;CommandLineRunner {&nbsp; &nbsp;@override&nbsp; &nbsp;Public void run(.... string){&nbsp; &nbsp; &nbsp;// Any code here gets called at the start of the app.&nbsp; }}这种方法主要用于使用一些初始数据引导应用程序。

慕无忌1623718

使用二级休眠缓存来缓存所有需要的数据库查询。为了在应用程序启动时缓存,我们可以在任何服务类中使用@PostContruct。语法将是:-@Servicepublic class anyService{&nbsp; @PostConstruct&nbsp; public void init(){&nbsp; &nbsp; &nbsp;//call any method&nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java