[英]How to cache data during application startup in Spring boot application
我有一個連接到SQL Server數據庫的Spring啟動應用程序。 在我的應用程序中使用緩存需要一些幫助。 我有一個CodeCategory表,其中包含許多代碼的代碼列表。 此表將每月加載一次,數據僅在一個月內更改一次。 我想在應用程序啟動時緩存整個表。 在對表的任何后續調用中,應從此緩存中獲取值,而不是調用數據庫。
例如,
List<CodeCategory> findAll();
我想在應用程序啟動期間緩存上面的數據庫查詢值。 如果存在類似List<CodeCategory> findByCodeValue(String code)
的DB調用,則List<CodeCategory> findByCodeValue(String code)
應從已緩存的數據中獲取代碼結果,而不是調用數據庫。
請告訴我如何使用spring boot和ehcache實現這一目標。
使用二級hibernate緩存來緩存所有必需的數據庫查詢。
對於應用程序啟動時的緩存,我們可以在任何Service類中使用@PostContruct。
語法將是: -
@Service
public class anyService{
@PostConstruct
public void init(){
//call any method
}
}
正如所指出的,ehcache設置需要一些時間,並且它與@PostConstruct
完全不兼容。 在這種情況下,請使用ApplicationStartedEvent
來加載緩存。
GitHub Repo: 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);
}
注意:其他方式有多種方式。 您可以根據自己的需要進行選擇。
使用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.
}}
此方法主要用於使用一些初始數據引導應用程序。
我的方法是定義一個通用的緩存處理程序
@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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.