一、調用方式
resttemplate需要手動創建RestTemplate bean,並且使用該bean進行http請求。使用該方式需要關注各種細節,如http header、body、response status等信息,使得代碼量較大,且需要手動處理各種異常。
RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.getForObject("http://localhost:8080/api/user/{id}", String.class, id);
而Feign默認集成了Ribbon和Eureka,簡化了代碼調用,並且提供了默認的請求攔截器和解碼器,使得調用變得更加簡潔、方便。使用該方式只需要定義介面並使用註解即可。
@FeignClient("user-service") public interface UserServiceClient { @GetMapping("/api/user/{id}") User getUserById(@PathVariable("id") Long id); }
二、介面定義
resttemplate需要手動定義請求參數、請求方法、請求url等,需要關注各種細節,使得代碼量較大,且維護成本較高。
String url = "http://localhost:8080/api/user"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity request = new HttpEntity(headers); ResponseEntity exchange = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
而在Feign中,只需要關注具體的業務方法,而無需關注請求參數、請求方法、請求url等細節,使得代碼更加簡潔、易於維護。
@FeignClient("user-service") public interface UserServiceClient { @GetMapping("/api/user") UserListResponse listUsers(@RequestParam("page") int page, @RequestParam("size") int size); }
三、請求方式
resttemplate支持多種請求方式,如GET、POST、PUT、DELETE等,且可以手動設置請求header、request body等信息。但是需要顯式指定請求方式,使得代碼量較大。
String url = "http://localhost:8080/api/user/{id}"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity request = new HttpEntity(headers); ResponseEntity exchange = restTemplate.exchange(url, HttpMethod.DELETE, request, String.class, id);
而在Feign中,只需要在介面方法上使用相應的註解即可,如@GetMapping、@PostMapping、@PutMapping、@DeleteMapping等。
@FeignClient("user-service") public interface UserServiceClient { @DeleteMapping("/api/user/{id}") void deleteUserById(@PathVariable("id") Long id); }
四、性能和可擴展性
由於resttemplate需要手動處理各種請求細節,使得代碼量較大,且可擴展性較差。而Feign在默認情況下已經提供了默認的請求攔截器和解碼器,使得代碼更加簡潔、易於維護,並且具有高可擴展性。
五、適用場景
resttemplate適合於對http請求有較為嚴格要求的場景,如對header、body、response status等信息有較高要求的場景。
Feign適合於微服務之間進行http調用的場景,尤其是針對於已經使用了Spring Cloud Ribbon和Eureka做負載均衡和服務治理的場景,使用Feign可以大大簡化調用方式,降低代碼量。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/285671.html