二、springcloud 服务调用 + 工程重构——笔记

1. 服务调用

服务调用

package wl.payment.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @author wl
 * @date 2021年5月26日 13:52:50
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
package wl.payment.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import wl.payment.entity.Payment;
import wl.util.CommonResult;

/**
 * @author wl
 * @date 2021年5月25日 22:33:31
 */
@RestController
@RequestMapping("/payment")
public class PaymentController {

    public static final String PAYMENT_URL = "http://localhost:8001";
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/create")
    public CommonResult createPayment(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/" + id, CommonResult.class);
    }
}
package com.test.wl.payment.controller;

import com.test.wl.payment.entity.Payment;
import com.test.wl.payment.service.PaymentService;
import com.test.wl.util.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author wl
 * @date 2021年5月25日 22:33:31
 */
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @PostMapping("/create")
    public CommonResult createPayment(Payment payment) {
        return paymentService.createPayment(payment);
    }

    @GetMapping("/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        return paymentService.selectById(id);
    }
}

将两个服务启动,再发送请求 http://localhost/payment/1

2. 工程重构(避免重复写 entity、util 等公共类)

(1)新建 module cloud-api-commons
(2)引入 cloud-api-commons 依赖

cloud-api-commons
        
            com.test.wl
            cloud-api-commons
            0.0.1-SNAPSHOT
            compile
        

运行效果:与上图一致



跟尚硅谷大佬(阳哥)一起学 springcloud
视频链接:https://www.bilibili.com/video/BV18E411x7eT?from=search&seid=11397380345672811627
我的项目地址:https://gitee.com/wl_projects/springcloud.git

你可能感兴趣的:(二、springcloud 服务调用 + 工程重构——笔记)