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<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;
    }

}

   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();
            }
        }
    }
}

 

posted @ 2018-04-29 11:41  _西兰花  阅读(13274)  评论(0编辑  收藏  举报