| 概述 网络请求时,可能会出现以下异常请求,如果想在发生异常的情况下使系统可用,就要进行容错处理。发生异常的情况可能有网络请求超时、url参数错误等等。 Spring Cloud Feign就是通过Fallback实现的,有以下两种方式: 1、@FeignClient.fallback = UserFeignFallback.class 指定一个实现Feign接口的类,当出现异常时调用该类中相应的方法 2、@FeignClient.fallbackFactory = UserFeignFactory.class 指定一个实现FallbackFactory<T>工厂接口的类 @FeignClient注解参数 name:指定FeignClient的名称 url:一般用于调试,可以手动指定@FeignClient的调用地址 configuration:Feign配置,可以实现自定义属性 fallback:自定义容错处理类,当调用远程接口失败或者超时时,会调用对应接口的容错逻辑,fallback指定的类必须实现@FeignClient标记的接口 path:定义当前FeignClient的统一前缀 实例  
 @FeignClient(name = "bos3dengine", path = "/api", fallback = FileRestServiceFallback.class,configuration = FeignMultipartSupportConfig.class)
public interface IFileRestService {
    /**
     * 上传模型文件
     * 
     * @param databaseKey
     *            数据库key
     * @param file
     *            文件对象
     * @param url
     *            文件下载地址
     * @param name
     *            模型名称
     * @param type
     *            模型类型
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value="/{databaseKey}/files",consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public BosCommonResponse uploadFile(@PathVariable(value = "databaseKey") String databaseKey,
            @RequestPart(value = "file", required = false) MultipartFile file,
            @RequestParam(value = "url", required = false) String url,
            @RequestParam(value = "name", required = false) String name, 
            @RequestParam(value = "type", required = false) String type);}
  
 @Component
public class FileRestServiceFallback implements IFileRestService {
    @Override
    public BosCommonResponse uploadFile(String databaseKey,MultipartFile file, String url, String name,String type){
        return BosCommonResponse.failure();
    }
} 当在实现了IFileRestService接口的Controller类中发生熔断,会调用fallback指向的类的具体方法。   |