在Spring Boot应用程序中的应用程序启动期间如何缓存数据

时间:2019-06-06 05:16:10

标签: java spring spring-boot caching ehcache

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

例如,

List<CodeCategory> findAll();

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

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

4 个答案:

答案 0 :(得分:0)

使用第二级休眠缓存来缓存所有必需的数据库查询。

对于在应用程序启动时进行缓存,我们可以在任何Service类中使用@PostContruct。

语法为:-

@Service
public class anyService{

  @PostConstruct
  public void init(){
     //call any method
 }
}

答案 1 :(得分:0)

如前所述,ehcache的建立需要花费一些时间,并且无法与@PostConstruct一起使用。在这种情况下,请使用ApplicationStartedEvent加载缓存。

GitHub存储库:spring-ehcache-demo


@Service
class CodeCategoryService{

   @EventListener(classes = ApplicationStartedEvent.class )
   public void listenToStart(ApplicationStartedEvent event) {
        this.repo.findByCodeValue("100");
   }

}

interface CodeCategoryRepository extends JpaRepository<CodeCategory, Long>{

    @Cacheable(value = "codeValues")
    List<CodeCategory> findByCodeValue(String code);
}


注意:其他人指出了多种方式。您可以根据自己的需要进行选择。

答案 2 :(得分:0)

使用 CommandLineRunner 界面。 基本上,您可以创建一个Spring @Component并实现CommandLineRunner接口。您将不得不覆盖它的run方法。 run方法将在应用程序的开头被调用。

@Component
public class DatabaseLoader implements 
CommandLineRunner {

   @override
   Public void run(.... string){
     // Any code here gets called at the start of the app.
  }}

此方法通常用于使用一些初始数据来引导应用程序。

答案 3 :(得分:0)

我的方法是定义一个通用的缓存处理程序

@FunctionalInterface
public interface GenericCacheHandler {

List<CodeCategory> findAll();
 }

及其实现如下

@Component
@EnableScheduling  // Important
public class GenericCacheHandlerImpl implements GenericCacheHandler {

@Autowired
private CodeRepository codeRepo;

private List<CodeCategory> codes = new ArrayList<>();

@PostConstruct
private void intializeBudgetState() {
    List<CodeCategory> codeList = codeRepo.findAll();
    // Any customization goes here
    codes = codeList;
}

@Override
public List<CodeCategory> getCodes() {
    return codes;
}
}

在下面的 Service 层中调用它

@Service
public class CodeServiceImpl implements CodeService {

@Autowired
private GenericCacheHandler genericCacheHandler;

@Override
public CodeDTO anyMethod() {
    return genericCacheHandler.getCodes();
}   
}
相关问题