RestTemplate实现跨服务请求
1. 前言
通常在多模块开发中,需要调用其他模块的服务。例如支付模块Payment,用户模块Consumer,用户模块需要调用支付模块的某些功能。此时两个模块分别运行在不同的端口上,前者8001,后者80。RestTemplate可以实现该功能
2. 实现
2.1 导依赖
版本version标签选择适合自己的
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.2 加Bean
RestTemplate为第三方bean,同样的套路
@Configuration
public class ApplicationContextConfig {
/**
* 这样IOC容器中会有一个RestTemplate对象
/
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
2.3 调用方法
被调用模块
此时支付模块运行在8001端口上,项目运行起来
下面是payment模块的控制器
@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {
@Autowired
private PaymentService paymentService;
@PostMapping("/create")
public CommonResult create(Payment payment) {
int result = paymentService.create(payment);
log.info("插入结果:{}", result);
if (result > 0) {
return new CommonResult(CodeConstant.CODE_200, "插入数据库成功", result);
} else {
return new CommonResult(CodeConstant.CODE_444, "插入数据库失败", null);
}
}
}
调用模块
Consumer模块调用上面的模块,使用postForObject进行url转发
@RestController
@RequestMapping("/consumer")
@Slf4j
public class OrderController {
@Autowired
private RestTemplate restTemplate;
private static final String PAYMENT_URL = "http://localhost:8001/payment";
@PostMapping("/payment/create")
public CommonResult create(Payment payment) {
log.info("consumer create...");
return restTemplate.postForObject(PAYMENT_URL + "/create", payment, CommonResult.class);
}
}