您的当前位置:首页正文

spring cloud feign配置

2024-11-28 来源:个人技术集锦
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-feign</artifactId>
   <version>1.3.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
  1. 添加配置
    我这边只配置了一个哨兵,用于兜底返回报错信息
feign:
  sentinel:
    enabled: true
  1. 代码层面
    3.1 在启动类上添加@EnableFeignClients注解
    3.2 添加feign调用类
// 接口调用
@FeignClient(value = "other-feign-project", path = "/v1", fallbackFactory = FeignFallbackFactory.class)
public interface BasicFeignClient {

    @ApiOperation(value = "feign测试")
    @PostMapping("/test/check")
    ResponseEntity<SimpleResponse<String>> selectCodeDetailByCodeId(  @ApiParam(value = "测试数据") @RequestBody TestModel  model);
}
// 异常返回
@Component
public class BasicFeignFallbackFactory implements FallbackFactory<BasicFeignClient> {
    public static final Logger logger = LoggerFactory.getLogger(BasicFeignFallbackFactory.class);

    @Override
    public BasicFeignClient create(Throwable cause) {
        return new BasicFeignClient() {
            @Override
            public ResponseEntity<SimpleResponse<String>> selectTest(TestModel  model) {
               throw new (FeignException) cause).getmsg();
            }
        };
    }
}
// 自定义异常
public class FeignException extends RuntimeException {
    private static final long serialVersionUID = 5609431427024976611L;
    private String msg;
    private final String code;
    private HttpStatus httpStatus;

    public FeignException(HttpStatus httpStatus, String code) {
        super(code);
        this.httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        this.code = code;
        this.httpStatus = httpStatus;
    }

    public FeignException(HttpStatus httpStatus, String code, String msg) {
        super(code);
        this.httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        this.code = code;
        this.msg = msg;
        this.httpStatus = httpStatus;
    }

    public FeignException(String code, Throwable cause) {
        super(code, cause);
        this.httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        this.code = code;
    }

    public FeignException(String code, String msg) {
        this.httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        this.code = code;
        this.msg = msg;
    }

    public String getCode() {
        return this.code;
    }

    public String getmsg() {
        return this.msg;
    }

    public HttpStatus getHttpStatus() {
        return this.httpStatus;
    }
}
// 使用
  private String getTest() {
  TestModel  model=new TestModel();
        ResponseEntity<SimpleResponse<String>> simpleResponseResponseEntity = basicFeignClient.selectTest(model);
        JSONObject responseBody = JSONUtil.parseObj(simpleResponseResponseEntity.getBody());
        return (String) responseBody.get("data");
    }
显示全文