REST官方网站
1.配置类
package com.atguigu.springcloud.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ApplicationContextConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
//相当于applactionContext.xml中
80端口controller中调用
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@RestController
@Slf4j
public class OrderController {
public static final String URL = "http://localhost:8001";
// 注入rest服务
@Resource
private RestTemplate restTemplate;
//post方式 restTemplate.postForObject 服务调用post方式请求的时候 需要在接收位置Payment添加@RequestBody注解
@PostMapping("/consumer/payment/create")
public CommonResult create(Payment payment){
return restTemplate.postForObject(URL+"/payment/create",payment,CommonResult.class);
}
//get方式
@GetMapping("/consumer/payment/{id}")
public CommonResult get(@PathVariable Long id){
return restTemplate.getForObject(URL+"/payment/get/"+id,CommonResult.class);
}
}
8001中controller使用
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@RestController
@Slf4j
public class PaymentController {
@Resource
private PaymentService paymentService;
@PostMapping(value = "/payment/create")
public CommonResult create(@RequestBody Payment payment) {
int num = paymentService.create(payment);
if (num == 0) {
return new CommonResult(444, "添加数据失败", null);
}
return new CommonResult(200, "添加数据成功", payment);
}
//@PathVariable可以用来映射URL中的占位符到目标方法的参数中
@GetMapping(value = "/payment/get/{id}")
public CommonResult create(@PathVariable Long id) {
Payment paymentById = paymentService.getPaymentById(id);
if (paymentById == null) {
return new CommonResult(444, "获取数据失败,失败id=" + id, null);
}
return new CommonResult(200, "获取数据成功", paymentById);
}
}



