暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

使用Hystrix实现微服务的熔断处理

香草物语博客 2021-07-21
423


Hystrix是Netflix开源的一个延迟和容错库,用于隔离访问远程系统、服务或者第三方库,防止级联失效,从而提升系统的可用性与容错性。


Hystrix基本使用


添加依赖


<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.8.RELEASE</version>
</dependency>


为启动类增加@EnableHystrix注解,从而为项目启用断路器支持


@SpringBootApplication
@EnableFeignClients
@EnableHystrix
public class MicroserviceConsumerMovieApplication {

public static void main(String[] args) {
SpringApplication.run(MicroserviceConsumerMovieApplication.class, args);
}

}


修改方法,增加容错能力


  @GetMapping("/user/{id}")
@HystrixCommand(fallbackMethod = "findByIdFallback",
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000"),
@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
},
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "1"),
@HystrixProperty(name = "maxQueueSize", value = "10")
})
public User findById(@PathVariable Long id) {
return userFeignClient.findById(id);
}

public User findByIdFallback(Long id, Throwable throwable) {
log.info(throwable.getMessage());
User user = new User();
user.setName("默认用户");
return user;
}


测试


我们断开此时的服务提供者,访问方法,可以看到进入了容错方法,并获取到了异常信息。

23314-9vlo6z29ll.png
文章转载自香草物语博客,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论