【问题标题】:how to Load Parameters from database when the application start and keep it in memory如何在应用程序启动时从数据库加载参数并将其保存在内存中
【发布时间】:2020-10-17 08:45:31
【问题描述】:

我需要从数据库表中加载一些数据并将其保存在内存中,以便在网络应用程序需要时使用。我正在使用 springboot 和 JPA/Hibernate。我猜这个想法是在启动时运行查询然后保持会话或某种缓存..

我想知道执行此操作的适当方法以及一些示例(如果可能)。

我做了类似的事情,但没有 spring 和 JPA,我不知道如何在这里应用它。

顺便说一句,我对此很陌生(springboot 和 jpa/hibernate) 提前致谢

【问题讨论】:

标签: java spring-boot hibernate jpa


【解决方案1】:

有很多方法可以实现这一点,例如您可以使用 PostConstruct 拉取、使用应用程序引导事件,您可以使用实现 SmartLifeCycle/Lifecycle 的 bean。

后期

@Component
public class SomeService {
   
    @PostConstruct
    public void init(){
      
     // pull data from JPA repository and store it
    }

}

使用生命周期接口

@Component
public class SomeService implements Lifecycle{
   
    @Override
    public void start(){
       // pull data using JPA and store it
    }
    //...

}

使用 ApplicationReadyEvent 监听器

@Component
public class SomeService implements ApplicationListener<ApplicationReadyEvent>  {
   
  @Override
  public void onApplicationEvent(ApplicationReadyEvent event) {
     // pull data using JPA and store it
  }
}

您也可以使用其他组合。

【讨论】:

  • 使用ehcache怎么样?
  • 您也可以使用它,由您决定将这些数据存储在哪里,在本地系统内存或远程计算机中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 2012-12-27
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
  • 2018-10-13
  • 1970-01-01
相关资源
最近更新 更多