简单演示下RestTemplate的基本使用。
RestTemplate是spring提供的一个远程调用工具,常常搭配Eureka使用,不过今天只单独演示RestTemplate。
更多用法请参照官方文档:RestTemplate (Spring Framework 5.3.22 API),不过用的更多的(在下觉得)一般是
getForObject() |
演示分为客户端和服务端两部分,这里主要演示消费端,因为RestTemplate一系列操作都在消费端完成。
1.在controller同级包下建了一个配置包,用于配置RestTemplate,配置文件名ApplicationContextConfig.config
内容如下:
@Configuration //声明这是个配置文件,使其能够被扫描到
public class ApplicationContextConfig {
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
2.controller内容如下:
@RestController
public class OrderController {
//这里是我们要调用的服务地址
//这里是我们要调用的服务地址
//这里是我们要调用的服务地址
public static final String PAYMENT_URL = "http://localhost:8001";
@Resource
private RestTemplate restTemplate;//注入RestTemplate
@GetMapping("/consumer/student/save")
public CommonResult<Student> create(Student student) {
return restTemplate.postForObject(PAYMENT_URL + "/student/save", student, CommonResult.class);
}
@GetMapping(value = "/consumer/student/get/{id}")
public CommonResult<Student> get(@PathVariable("id") int id){
//此处拼接完整请求路径并开始调用另一服务即可
return restTemplate.getForObject(PAYMENT_URL + "/student/get/"+id, CommonResult.class);
}
}
或者使用下面一种方式更简单一些,直接在controller中直接new一个RestTemplate对象:
@RestController
public class OrderController {
public static final String PAYMENT_URL = "http://localhost:8001";//单机版
//public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
RestTemplate restTemplate=new RestTemplate();
@GetMapping("/consumer/student/save")
public CommonResult<Student> create(Student student) {
return restTemplate.postForObject(PAYMENT_URL + "/student/save", student, CommonResult.class);
}
@GetMapping(value = "/consumer/student/get/{id}")
public CommonResult<Student> get(@PathVariable("id") int id) {
int a = 0;
return restTemplate.getForObject(PAYMENT_URL + "/student/get/" + id, CommonResult.class);
}
}
上述请求路径拼接完成后一定要正确,我的服务端路径是这样的:
@RequestMapping(value = "/student/get/{id}")
public CommonResult<Student> selectById(@PathVariable int id) {
return new CommonResult(200, "查询成功,serverPort:"+serverPort, studentService.selectById(id));
}
时间问题,内容较为粗糙,还望各位同行指出不足之处。