http請求做遠程調用是與語言無關的調用,只要知道對方的ip,端口,接口路徑,請求參數即可
啟動類中配置:
@Beanpublic RestTemplate restTemplate(){return new RestTemplate();}
Sevice中書寫方法
get
@Autowiredprivate RestTemplate restTemplate;public Order queryOrderById(Long orderId) {// 1.查詢訂單Order order = orderMapper.findById(orderId);//2.查詢到了用戶idLong userId = order.getUserId();//發起一個請求訪問http://localhost:8081/user/5String url ="http://localhost:8081/user/"+userId;User user = restTemplate.getForObject(url, User.class);//封裝order.setUser(user);// 4.返回return order;}
建議
從Spring 5開始,官方推薦使用WebClient
代替RestTemplate
作為進行HTTP請求的工具。WebClient
是一個非阻塞、響應式的HTTP客戶端,更適合于構建高性能、異步的應用程序。因此,在新的Spring項目中,建議使用WebClient
替代RestTemplate
。
使用WebClient
發送GET請求的示例:
WebClient webClient = WebClient.create();
String url = "https://api.example.com/users";
String responseBody = webClient.get().uri(url).retrieve().bodyToMono(String.class).block();
使用WebClient
發送GET請求到指定的URL,并通過bodyToMono
方法將響應體轉換為字符串類型。最后,通過調用block
方法阻塞獲取響應體的內容。