返回 导航

SpringBoot / Cloud

hangge.com

SpringCloud - 服务容错保护组件Hystrix的使用详解5(命令名称、分组、线程池划分)

作者:hangge | 2020-07-16 08:10

五、命令名称、分组、线程池划分

1,设置命令名称

    默认情况下,@HystrixCommand 注解标注的方法名即为命令名称。我们也可以通过该注解的 commandKey 属性设置命令名称:
@Service
public class UserService {
    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(commandKey = "getUserById")
    public User getUserById(Long id) {
        return restTemplate.getForObject("http://USER-SERVICE/users/{1}", User.class, id);
    }
}

2,设置分组名称

    默认情况下,命令组名为 @HystrixCommand 注解方法所在类的名称。我们也可以通过该注解的 groupKey 属性设置分组名称:
命令组作用:
  • Hystrix 会根据组来组织和统计命令的告警、仪表盘等统计信息。
  • 此外 Hystrix 命令默认的线程划分也是根据命令分组来实现的。默认情况下,Hystrix 会让相同组名的命令使用同一个线程池,所以我们需要在创建 Hystrix 命令时为其指定命令组名来实现默认的线程池划分。
@Service
public class UserService {
    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(groupKey = "UserGroup")
    public User getUserById(Long id) {
        return restTemplate.getForObject("http://USER-SERVICE/users/{1}", User.class, id);
    }
}

3,设置线程池名称

    Hystrix 还提供了 HystrixThreadPoolKey 属性来对线程池进行设置,通过它我们可以实更细粒度的线程池划分:
    如果 Hystrix 的线程池分配仅仅依靠命令组来划分,那么它就显得不够灵活了。因为多个不同的命令可能从业务逻辑上来看属于同一个组,但是往往从实现本身上需要跟其他命令进行隔离。
@Service
public class UserService {
    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(threadPoolKey = "getUserByIdThread")
    public User getUserById(Long id) {
        return restTemplate.getForObject("http://USER-SERVICE/users/{1}", User.class, id);
    }
}
评论

全部评论(0)

回到顶部