2017-04-18 81 views
0

我有一个REST API,我想调用一个从csv文件创建TreeMap的方法,并且我希望为每个API调用的其余部分使用TreeMap。所以我只是想要调用该方法来设置TreeMap并且想要使用TreeMap来处理其余的API调用。如何在控制器中只调用一次calla方法

我创建映像树的方法是

public void createTreeMap(){ 

CSVReader reader = new CSVReader(new FileReader("C:\\Users\\result.csv"), ',' , '"' , 1); 
        TreeMap <Integer,ArrayList<Long>> result=new TreeMap <Integer,ArrayList<Long>>(); 
        //Read CSV line by line and use the string array as you want 
        String[] nextLine; 
        while ((nextLine = reader.readNext()) != null) { 
         if (nextLine != null) { 
          //Verifying the read data here 
          ArrayList<Long> result_01 = new ArrayList<Long>(); 

          for(int k=0;k<nextLine[1].replace("[", "").replace("]", "").replace(" ", "").split(",").length;k++){ 
           result_01.add(Long.parseLong(nextLine[1].replace("[", "").replace("]", "").replace(" ", "").split(",")[k])); 
          } 


          result.put(Integer.parseInt(nextLine[0]), result_01); 



         } 
        } 

} 

所以下面是REST API控制器

@RestController 
public class HomeController { 



@RequestMapping(value="/api/sid",produces={MediaType.APPLICATION_JSON_VALUE},method=RequestMethod.GET) 
    public ResponseEntity<Map<String, List<Model>>> getid(@RequestParam("sid") int sid) { 




     Map<String, List<Model>> Map = new HashMap<String, Object>(); 
     List<Model> model=new List<Model>(); 
     model=get_model(); 
     Map.put("hi",model) 

     return new ResponseEntity<Map<String, List<Model>>>(Map,HttpStatus.OK); 

    } 


    @ResponseBody 

    public List<Model> get_model(){ 
     List list =new List<Model>(); 
    //here I have to use the treemap 

     return list; 



    } 

    } 

我可以创建树当每次API代替called.but我的时间地图需要创建它只有一次,并访问响应正文get_model方法。任何帮助表示赞赏。

+0

使用缓存怎么样? –

+0

我应该在哪里定义缓存? – RKR

+0

https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html –

回答

1

使用单例bean,即创建另一个bean来从csv文件和Bean的成员变量中的TreeMap创建TreeMap。

@Bean 
public class RefData{ 
    public TreeMap<Object> treeMap; 

    public TreeMap<Object> getData(){ 
     if(this.treeMap == null){ 
      //read csv file & prepare TreeMap & store it in this.treeMap 
     } 
     return this.treeMap; 
    } 
} 
+0

所以这个bean将在控制器本身的权利 – RKR

+1

更好的是有另一个类并注入你的控制器和无论何时需要 – JRR

相关问题