java-项目加载时将数据存储到内存中

     1、获取数据库数据并存储在Map对象中

package com.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class RegionServiceImpl  { //implements RegionService {

    @Autowired
    UserRepository userRepository;
    public static Map regionMap = new HashMap();

    public Map initRegion(){
        if(regionMap.isEmpty()){
            List regionList = userRepository.findAll();
            for(Users r : regionList){
                regionMap.put(r.getId(),r.getName()+","+r.getSex());
            }
        }
        return  regionMap;
    }
    public Map getAllRegionMap(){
        return getRegionMap();
    }

    public static Map getRegionMap() {
        return regionMap;
    }

    public static void setRegionMap(Map regionMap) {
        RegionServiceImpl.regionMap = regionMap;
    }

}

   2、在项目启动时加载方法

package com.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Autowired
    RegionServiceImpl regionService;
  
/**
* 线程启动
*/

public void start(){
new Thread(new xiancheng()).start();
        System.out.println(0);
    }
    @Override
    public void run(String... var1) throws Exception{

        regionService.initRegion();
        start();
        System.out.println("初始化完成");
    }
}

  3、使用线程设置定时刷新数据

package com.demo;

public class xiancheng implements Runnable{


    public void run() {
        RegionServiceImpl regionService = new RegionServiceImpl();
        while (true) {
            regionService.initRegion();
            try {
                System.out.println(111);
                Thread.sleep(10 * 60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

 

转载于:https://www.cnblogs.com/daxiaxia/p/8970690.html

你可能感兴趣的:(java-项目加载时将数据存储到内存中)