一、实现方式
在一个服务中使用RestTemplate模拟服务器向另一个服务发起http的Get或Post请求
二、具体实现
在配置类(含有@SpringBootApplication注解,如启动类)中使用Bean的方式将RestTemplate注入SpringBoot容器
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
在Service业务层中注入RestTemplate对象
@Autowired
private RestTemplate restTemplate;
使用RestTemplate的getForObject()方法对另一个服务发起Get请求;同理使用postForObject()方法发起Post请求(函数里面有两个参数url:所请求的服务的URL形如http://localhost:8080/user/ 另一个参数为指定将返回的json格式数据转化为类对象形如User.class)
User user = restTemplate.getForObject("http://localhost:8080/user",User.class);