一,为什么要编写失败降级逻辑
业务失败后,不能直接报错,而应该返回用户一个提示或者默认结果
二,实现步骤
1,自定义类实现FallbackFactory接口
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;@Slf4j
public class AdClientFallbackFactory implements FallbackFactory<FeignClient客户端名称> {//重写里面的方法 直接编写降级逻辑就可以@Overridepublic UserClient create(Throwable throwable) {return new UserClient() {@Overridepublic User findById(Long id) {log.error("查询异常", throwable);return new User(); //不要返回NUll 容易造成空指针异常}};}
}
2,将AdClientFallbackFactory 注册为一个Bean
@Bean
public AdClientFallbackFactory AdClientFallbackFactory(){return new AdClientFallbackFactory();
}
3,在feing项目中的XXXClient接口中使用AdClientFallbackFactory:
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;@FeignClient(value = "adservice", fallbackFactory = AdClientFallbackFactory.class)
public interface AdClient {@GetMapping("/Ad/{id}")User findById(@PathVariable("id") Long id);
}