feign自定义fallback方法

client端的controller

@RestController
public class HelloWorldController {

  @Autowired
  private ServerFeignClient serverFeignClient;

  @GetMapping("/hello")
  public BaseResult hello(){
      System.out.println("aaaaa");
      System.out.println("--------");
    return serverFeignClient.hello();
  }
}

client端的interface

@FeignClient(name = "ZONESEA-SERVER-WZSC" , fallbackFactory = ServerFeignClientFallBackFactory.class )
public interface ServerFeignClient {

  @RequestMapping(value = "/hello", method = RequestMethod.GET)
  BaseResult hello();
}

client端调用失败的具体方法

@Component
public class ServerFeignClientFallBackFactory implements FallbackFactory<ServerFeignClient> {

  @Override
  public ServerFeignClient create(Throwable throwable) {
    return new ServerFeignClient() {
      @Override
      public BaseResult hello() {
        BaseResult baseResult =  new BaseResult<>();
        baseResult.setCode(-1);
        baseResult.setMessage("fail");
        return baseResult;
      }
    };
  }
}

在服务器值开启client端的情况下,会因为不能调用service端而去调用自定义调用失败的方法.这里需要注意的是,feign在后期的版本里面自带hystrix和ribbon的.这里需要在配置文件中把hystrix开启然后这个回调方法才会生效的.

#开启hystrix配置
feign:
  hystrix:
    enabled: true

你可能感兴趣的:(springboot)