SpringBoot项目之间通过restTempalte进行访问

创建spring的配置类
在里面注入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) {
     
        //插入数据,写数据在底层一般用post
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
     
        //读数据,用get
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }
}

你可能感兴趣的:(spring,boot)