Feign 接口的多態
    2023-04-10 18:34:31 來源: 騰訊云


    (資料圖片僅供參考)

    接口多態

    在Feign中,接口多態可以讓我們通過一個接口的引用來調用不同的實現類,從而提高代碼的靈活性和可擴展性。

    例如,我們有一個支付服務接口,它有多種支付方式,我們可以使用接口多態來實現這些支付方式的調用。

    定義接口

    首先,我們需要定義一個支付服務接口,其中包含了多種支付方式的方法。

    public interface PaymentService {    @PostMapping("/pay")    PaymentResponse pay(@RequestBody PaymentRequest request);}public class PaymentRequest {    private String paymentType;    private Double amount;    //...}public class PaymentResponse {    private String status;    private String message;    //...}

    在上面的示例中,我們定義了一個名為PaymentService的接口,其中包含了支付方法pay,并定義了請求參數PaymentRequest和響應參數PaymentResponse。

    實現接口

    接下來,我們可以實現支付服務接口,針對不同的支付方式提供不同的實現。

    @FeignClient(name = "alipay-service")public interface AlipayService extends PaymentService {}@FeignClient(name = "wechatpay-service")public interface WechatpayService extends PaymentService {}

    在上面的示例中,我們分別定義了支付寶支付服務和微信支付服務,它們都實現了PaymentService接口,從而可以使用接口多態來調用不同的支付方式。

    使用接口多態

    最后,我們可以使用接口多態來調用不同的支付方式,例如:

    public class PaymentController {    private PaymentService paymentService;    public PaymentController(PaymentService paymentService) {        this.paymentService = paymentService;    }    @PostMapping("/pay")    public PaymentResponse pay(@RequestBody PaymentRequest request) {        return paymentService.pay(request);    }}@RestControllerpublic class AlipayController {    private PaymentController paymentController;    public AlipayController(AlipayService alipayService) {        paymentController = new PaymentController(alipayService);    }    @PostMapping("/alipay/pay")    public PaymentResponse pay(@RequestBody PaymentRequest request) {        return paymentController.pay(request);    }}@RestControllerpublic class WechatpayController {    private PaymentController paymentController;    public WechatpayController(WechatpayService wechatpayService) {        paymentController = new PaymentController(wechatpayService);    }    @PostMapping("/wechatpay/pay")    public PaymentResponse pay(@RequestBody PaymentRequest request) {        return paymentController.pay(request);    }}

    在上面的示例中,我們定義了一個名為PaymentController的控制器,它接收一個PaymentService接口的實現類,并提供了一個名為pay的方法來調用支付服務。

    然后,我們分別定義了支付寶控制器和微信支付控制器,并將它們的構造函數注入了AlipayService和WechatpayService接口的實現類,從而使用接口多態來調用不同的支付方式。

    關鍵詞:
    責任編輯: 梅長蘇