2017-04-18 10 views
0

私はREST APIを持っており、csvファイルからTreeMapを作成するメソッドを呼びたいので、残りの各API呼び出しのためにTreeMapを使用したいと思います。このメソッドを呼び出してTreeMapを設定し、残りのAPI呼び出しにTreeMapを使用したいとします。そこで、以下コントローラ内でメソッドを1回呼び出す方法

のTreeMapを作成するための私の方法がある

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



         } 
        } 

} 

は、私は木がAPIはそのIの代わりにcalled.butされるたびにマップを作成することができます

@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・コントローラーですそれを一度しか作成せず、応答本体のget_modelメソッドにアクセスする必要があります。

+0

キャッシュを使用するとどうなりますか? –

+0

どこでキャッシュを定義すればよいですか? – RKR

+0

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

答えて

1

シングルトンビーンを使用します。つまり、別のBeanを作成してcsvファイルからTreeMapを作成し、TreeMapをBeanのメンバー変数に作成します。

@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

関連する問題