OpenFeign fallback 兜底返回

一、场景

远程调用出错,有兜底返回值

二、环境搭建

1、引入依赖 Sentinel

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

2、配置feign yaml

feign:
  sentinel:
    enabled: true

三、兜底返回

1、创建兜底返回类

feign.fallback.ProductFeignClientFallBack

2、实现远程调用接口(feign客户端)

package com.wt.order.feign.fallback;
import java.math.BigDecimal;

import com.wt.order.feign.ProductFeignClient;
import com.wt.product.bean.Product;
import org.springframework.stereotype.Component;

@Component
public class ProductFeignClientFallBack implements ProductFeignClient {
    // 兜底返回
    @Override
    public Product getProductById(Long id) {
        Product product = new Product();
        product.setId(id);
        product.setPrice(new BigDecimal("0"));
        product.setProductName("未知产品");
        product.setNum(0);

        return product;
    }
}

注意:别忘记注入

3、在feigin客户端,开启fallback

fallback=fallback类

package com.wt.order.feign;

import com.wt.order.feign.fallback.ProductFeignClientFallBack;
import com.wt.product.bean.Product;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = "services-product", fallback = ProductFeignClientFallBack.class)
public interface ProductFeignClient {
    @GetMapping("product/{id}")
    Product getProductById(@PathVariable Long id);
}

 

posted @ 2025-06-09 21:34  市丸银  阅读(59)  评论(0)    收藏  举报