Hystrix 熔断器

Hystrix 是Netflix开源的一个延迟和容错库,用于隔离访问远程服务,防止出现级联失败

一、Hystrix 的定义

二、Hystrix 的原理

在分布式式系统中应用熔断器后,服务调用方可以自己进行判断某些服务反应慢或者存在

大量超时的情况,能够主动熔断,防止整个系统被拖垮。当情况好转时,可以自动重连,

以实现弹性容错。

通过断路的方式,可以将后续的请求直接拒绝掉,一段时间后允许部分请求通过。

三、Hystrix 的具体使用

1、引入依赖 (在服务的消费方 引入Hystrix 依赖)

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

2、开启熔断

3、改造消费者

@Component
public class UserDao {

    @Autowired
    private RestTemplate restTemplate;

    private static final Logger logger = LoggerFactory.getLogger(UserDao.class);

    @HystrixCommand(fallbackMethod = "queryUserByIdFallback")
    public User queryUserById(Long id){
        long begin = System.currentTimeMillis();
        String url = "http://user-service/user/" + id;
        User user = this.restTemplate.getForObject(url, User.class);
        long end = System.currentTimeMillis();
        // 记录访问用时:
        logger.info("访问用时:{}", end - begin);
        return user;
    }

    public User queryUserByIdFallback(Long id){
        User user = new User();
        user.setId(id);
        user.setName("用户信息查询出现异常!");
        return user;
    }
}

@HystrixCommand(fallbackMethod="queryUserByIdFallback"):声明一个失败回滚处理函数queryUserByIdFallback,当queryUserById执行超时(默认是1000毫秒),就会执行fallback函数,返回错误提示。

4、改造服务提供者

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User queryById(Long id) throws InterruptedException {
        // 为了演示超时现象,我们在这里然线程休眠,时间随机 0~2000毫秒
        Thread.sleep(new Random().nextInt(2000));
        return this.userMapper.selectByPrimaryKey(id);
    }
}

5、启动测试

结果:

====================华丽的分割线=============================

优化

虽然熔断实现了,但是我们的重试机制似乎没有生效,是这样吗?

其实这里是因为我们的Ribbon超时时间设置的是1000ms:

而Hystix的超时时间默认也是1000ms,因此重试机制没有被触发,而是先触发了熔断。

所以,Ribbon的超时时间一定要小于Hystix的超时时间。

我们可以通过hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds来设置Hystrix超时时间。

hystrix:
  command:
      default:
        execution:
          isolation:
            thread:
              timeoutInMillisecond: 6000 # 设置hystrix的超时时间为6000ms

猜你喜欢

转载自www.cnblogs.com/houchen/p/12056897.html
今日推荐