基本配置
配置pom文件,配置yml文件,创建启动类,省略
复制entity类到消费者
后期会把公共类提取出来,此处省略,意思是在消费者模块里面也需要用到实体类,在controller层里面可以清晰的看到
创建配置类,注入RestTemplate
@Configuration
public class ApplicationContextConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
创建controller层
@RestController
@Slf4j
public class OrderController {
public static final String PAYMENT_URL = "http://localhost:8001";
@Resource
private RestTemplate restTemplate;
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment) {
return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
}
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
}
}
RestTemplate是一种简单便捷的访问restul服务模板类,是spring提供的用于访问Rest服务的客户端模板工具急,提供了多种便捷访问远程Http服务的方法。
(url,requestMap,ResponseBean.class)这三个参数分别代表REST请求地址,请求参数,http响应被转换成的对象类型。
测试


注意:

可以看到程序返回插入数据成功,但是数据库里面却没有数据,需要在生产者controller里面加上@RequestBody注解才能生效
加上注解之后再试一次

可以看到数据正确插入进来了

339

被折叠的 条评论
为什么被折叠?



