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
方法阻塞获取响应体的内容。