对于order 不需要连接数据库等方法,只需要对payment业务进行调用,实现横向调用的是RestTemplate
- 新建maven,配置pom,配置application,建好文件目录
- 注入 RestTemplate
@Configuration
public class ApplicationContextConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();//用来横向调用payment业务类
}
}
- 配置cotroller
@Slf4j
@RestController
public class OrderController {
public static final String PAYMENT_URL = "http://localhost:8001/payment/";
@Resource
RestTemplate template;// 使用restTemplate访问restful接口 参数(url,请求参数,http响应被转换成的对象)
@GetMapping("/consumer/payment/create") // 注意是GET
public CommonResult<Payment> create(Payment payment){
System.out.println(payment);
return template.postForObject(PAYMENT_URL+"create",payment, CommonResult.class);
}
@GetMapping("/consumer/payment/get/{id}") // 注意是GET
public CommonResult<Payment> get(@PathVariable long id){
return template.getForObject(PAYMENT_URL + "get/"+id, CommonResult.class);
}
}
- 确保将http参数传入方法中,为payment的controller添加@RequestBody注解
@Slf4j
@RestController
public class PaymentController {
@Resource
private IPaymentService paymentService;
@PostMapping("/payment/create")
public CommonResult<Payment> create(@RequestBody Payment payment){
System.out.println(payment);
boolean result = paymentService.save(payment);
if (result){
return new CommonResult<Payment>(200,"插入数据库成功");
}else{
return new CommonResult<Payment>(444,"插入数据库失败");
}
}
@GetMapping("/payment/get/{id}")
public CommonResult<Payment> get(@PathVariable("id") long id){
Payment result = paymentService.getById(id);
if (result!=null){
return new CommonResult<Payment>(200,"查询数据库成功",result);
}else{
return new CommonResult<Payment>(444,"查询数据库失败",null);
}
}
}
依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>SpringCloud</artifactId>
<groupId>com</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ConsumerOrder80</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
</project>