执行流程:请求失败,先执行多次重试,重试还不行就进入断路器熔断
使用回退模式,当远程服务调用失败时,服务消费者将执行替代代码路径,以尝试通过另一种方式执行操作,而不是生成异常。
步骤一 配置开启
feign:
client:
config:
default:
connectTimeout: 3000
readTimeout: 3000
loggerLevel: BASIC
hystrix:
enabled: true # 开启断路器
hystrix:
command:
myusers-service:
execution:
isolation:
thread:
timeoutInMilliseconds: 6000 #应大于上面的feign超时,否则上面的超时不起作用,直接走断路器了
步骤二 实现在服务失败时调用的回退方法
@Component
public class JSONPlaceHolderFallback implements JSONPlaceHolderClient {
@Override
public List<Post> getPosts() {
return Collections.emptyList();
}
@Override
public Post getPostById(Long postId) {
return null;
}
}
步骤三 让 Feign 知道已经提供了回退方法,我们还需要在@FeignClient*注释中设置我们的回退类*
@FeignClient(value = "jplaceholder", url = "https://jsonplaceholder.typicode.com/", fallback = JSONPlaceHolderFallback.class)
public interface JSONPlaceHolderClient {
@RequestMapping(method = RequestMethod.GET, value = "/posts")
List<Post> getPosts();
@RequestMapping(method = RequestMethod.GET, value = "/posts/{postId}", produces = "application/json")
Post getPostById(@PathVariable("postId") Long postId);
}
效果
重试
回退结果