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

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

java-项目加载时将数据存储到内存中
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<Integer,String> regionMap = new HashMap<Integer, String>();

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

    public static Map<Integer, String> getRegionMap() {
        return regionMap;
    }

    public static void setRegionMap(Map<Integer, String> regionMap) {
        RegionServiceImpl.regionMap = regionMap;
    }

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

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

java-项目加载时将数据存储到内存中
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("初始化完成");
    }
}
java-项目加载时将数据存储到内存中

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

java-项目加载时将数据存储到内存中
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();
            }
        }
    }
}
java-项目加载时将数据存储到内存中

 

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

上一篇:asp.net mvc 3 配置全局错误处理 Web.config中设置CustomError


下一篇:js常用的遍历函数(转载自https://blog.csdn.net/zyf1550397589/article/details/81126401)