SSM启动服务时将数据存入缓存

使用场景:

页面要调用的是后端数据量非常大的接口,并且时间较长,这时项目没有缓冲功能(例如redis),那么如果每次实时取数据给客户的体验是非常不好的,这时我们可以按如下代码,在初始化的时候就去数据库取数据,然后封装到map或list。。。中,这样什么时候用直接就可以拿到数据了。

package com.jeeplus.modules.ins.cache;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

/**
 * 启动服务时将字典存入缓存
 * @author 宁无敌
 *
 */
@Component
public class CacheListener implements ApplicationListener<ContextRefreshedEvent>{
    private Logger log = LoggerFactory.getLogger(CacheListener.class);

    
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if(event.getApplicationContext().getParent() == null){
        log.info("项目启动完成,准备加载字典...");
        CacheManager.setDict();
        log.info("准备获取基金列表");
        CacheManager.setFundList();
        log.info("准备获取银行列表");
        CacheManager.setBankList();
        log.info("准备获取Ta列表");
        CacheManager.setTaList();
        
        }
    }
    
}

思路:拿Servlet 举例→ 在init()方法中就去调用数据库取数据,然后客户在调用doPost()或doPost()的时候就可以拿到init()方法中获取的数据了。

原文地址:https://www.cnblogs.com/cuijiade/p/9268265.html