微服务 在 Java 代码中发送 http 请求(跨服务远程调用)
1. 注册 RestTemplate 对象到 Spring 容器中(Bean 的注入只能放在配置类里,而启动类本身就是配置类)
@SpringBootApplication
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
2. 在代码中发送请求
①用 @Autowired 将 bean 对象注入进来
@Autowired
private RestTemplate restTemplate;
②利用 restTemplate 对象发送请求(以 get 为例)
String url = "http://localhost:8081/user/1";
//参数一:请求路径字符串 参数二:请求返回的结果是json风格,但我们想要的是对象。所以参数二的作用是自动帮我们把json转成对应的对象类型
User user = restTemplate.getForObject(url, User.class);
System.out.println(user);