2017-04-18 78 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

相關問題