分为以下4步:

1. 添加依赖: sentinel,feign
2. 配置feign允许sentinel
3. 编写: feign,请求客户端
4. 为客户端添加(sentinel)异常处理类

1.添加依赖: sentinel,feign


        org.springframework.cloud
        spring-cloud-starter-openfeign


        org.springframework.cloud
        spring-cloud-starter-alibaba-sentinel

2.配置feign允许sentinel

feign:
  sentinel:
    enabled: true

3.编写: feign,请求客户端

@FeignClient(name = "user-center")
public interface UserCenterFeignClient {
    public ApiResult findBy(Integer id);
    public ApiResult getDetail(User user);
}

4.为客户端添加(sentinel)异常处理类

方式(1).

// 用户中心 Feign 接口
@FeignClient(name = "user-center",fallback = FeignClientFallback.class)
public interface UserCenterFeignClient {
    public ApiResult findBy(Integer id);
    public ApiResult getDetail(User user);
}

// 用户中心 Feign异常接收处理类
@Component
public class UserCenterFeignClientFallback implements UserCenterFeignClient {
    @Override
    public ApiResult findBy(Integer id) {
        return ApiResult.error("异常");
    }

    @Override
    public ApiResult getDetail(User users) {
        return ApiResult.error("异常");
    }
}

方式(2).

// 接口
@FeignClient(name = "user-center",fallbackFactory = FeignClientFallback.class)        // 方法上可以拿到异常
public interface UserCenterFeignClient {
    public ApiResult findBy(Integer id);
    public ApiResult getDetail(User user);
}

// 异常处理类
@Component
@Slf4j
public class UserCenterFeignClientFallbackFactory implements FallbackFactory {

    // 用户中心 Feign异常接收处理类
    @Override
    public UserCenterFeignClient create(Throwable throwable) {
        return new UserCenterFeignClient() {
            @Override
            public ApiResult findBy(Integer id) {
                log.warn("异常",throwable);
                return ApiResult.error("Sentinel 异常");
            }

            @Override
            public ApiResult getDetail(User users) {
                return ApiResult.error("Sentinel 异常");
            }
        };
    }

}