SprirngBoot微服務之間的交互—— restTemplate


一 例:需要在storage服務中請求utils服務的某個接口(兩個服務都已向同一台eureka server 注冊)

步驟:

1 在utils創建需被調用的接口

@RestController
@RequestMapping("/api")
public class CheckIPResource {
      @PostMapping("/checkip")
      public String checkIP(@RequestBody TestEntity testEntity) {
          //處理數據
   // 返回結果         return "404";     } }

2 在storage的主類里創建restTemplate

位置: com.ejtone.ejt1.StorageApp
​
public class StorageApp {
    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){ return new RestTemplate(); }
}

3 在storage需要調用utils接口的地方去調用

public class CheckIpService {
​
    @Autowired
    private RestTemplate restTemplate;
    
    public void testFrom(TestEntity testEntity){
    
      // postForObject   請求方式:post  常用的請求方式還有get,具體見下方第二點
      // http://utils/api/checkip  utils:是utils微服務向eureka server注冊時的名稱,后接具體位置
      // new HttpEntity<>(testEntity) 請求體 --可帶請求頭,具體見下方第三點
      //String.class 請求響應返回后的數據的類型
      restTemplate.postForObject("http://utils/api/checkip",
             new HttpEntity<>(testEntity),            String.class);   } }

二 請求方式除了上面使用的post之外,還有getForObject:

// 參數url是http請求的地址
// Class responseType  請求響應返回后的數據的類型
// String... urlVariables 請求中需要設置的參數
RestTemplate.getForObject(String url, Class responseType, String... urlVariables)
​
例如下方,url上帶着一個參數{id},最后執行該方法會返回一個String類型的結果,后面的id是請求的一個具體變量。
template.getForObject(url + "get/{id}", String.class, id);

三 HttpEntity<>(請求體,請求頭)

public class ParService {
    @Autowired
    private RestTemplate restTemplate;
    
    public Par setPar(TxtFileVM txtFileVM, HttpServletRequest request) {
      //創建一個請求頭    HttpHeaders headers = new HttpHeaders();           Enumeration<String> headerNames = request.getHeaderNames();           while (headerNames.hasMoreElements()) {               String key = (String) headerNames.nextElement();               String value = request.getHeader(key);               headers.add(key, value);           }           txtPath = restTemplate.postForObject("http://storage/api/create/txtfile",                    new HttpEntity<>(txtFileVM,headers),                    String.class); }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM