一:需要调用的微服务, 就和平时写的微服务一样, 能实现数据的增删改查就行。
@RequestMapping("/add")
public CommonResult add(Payment payment) {
@RequestMapping("/getPayment")
public CommonResult getPayment(Long id) {
二:消费者的实现
- 将restTemplate注入到容器里面
@Configuration
public class ApplicationConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
};
}
在controller里面使用它调用之前的微服务
@Autowired
private RestTemplate restTemplate;
public static final String PAYMENT_URL = "http://localhost:8001" ;
@GetMapping("/consumer/payment/add")
public ResponseEntity<CommonResult> add(Payment payment){
return restTemplate.postForEntity(PAYMENT_URL + "/add", payment, CommonResult.class );
}
@GetMapping("/consumer/payment/getPayment")
public ResponseEntity<CommonResult> getPayment(@RequestParam("id") int id){
return restTemplate.getForEntity(PAYMENT_URL + "/getPayment?id="+id, CommonResult.class );
}
此时, 我们使用消费者的端口号去访问
http://localhost/consumer/payment/getPayment?id=1
结果如下
但是插入会出现问题,显示插入成功但是数据库里面的数据为null
此时 解决这个问题的方法就是在8001里面添加@RequestBody