在Spring Boot应用程序中如何在应用程序启动期间缓存数据 [英] How to cache data during application startup in Spring boot application

查看:109
本文介绍了在Spring Boot应用程序中如何在应用程序启动期间缓存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Spring boot Application connecting to SQL Server Database. I need some help in using caching in my application. I have a table for CodeCategory which has a list of codes for Many codes. This table will be loaded every month and data changes only once in a month. I want to cache this entire table when the Application starts. In any subsequent calls to the table should get value from this cache instead of calling the Database.

例如,

List<CodeCategory> findAll();

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

I want to cache the above DB query value during application startup. If there is a DB call like List<CodeCategory> findByCodeValue(String code) should fetch the code result from the already Cached data instead of calling the Database.

请让我知道如何处理

推荐答案

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

My way is to define a generic cache handler

@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
public class CodeServiceImpl implements CodeService {

@Autowired
private GenericCacheHandler genericCacheHandler;

@Override
public CodeDTO anyMethod() {
    return genericCacheHandler.getCodes();
}   
}

这篇关于在Spring Boot应用程序中如何在应用程序启动期间缓存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆