hystrix使用时会在方法上增加一个@HystrixCommand注解,类似下面代码
@RequestMapping("/demo1/{userId}")
@HystrixCommand(
commandProperties = {
//2秒后调用还未返回就熔断
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",
value = "2000")
}
)
public String demo(@PathVariable Integer userId){
String url = "http://andy-provide/demo/"+userId;
return restTemplate.getForObject(url, String.class);
}
@RequestMapping("/demo2/{userId}")
@HystrixCommand(
//2秒后调用还未返回就熔断
commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",
value = "2000")
}
)
public String demo1(@PathVariable Integer userId){
String url = "http://andy-provide/demo1/"+userId;
return restTemplate.getForObject(url, String.class);
}
这里的demo1和demo2接口都使用了@HystrixCommand注解,这样在进行请求时hystrix有一个默认的线程池,demo1发生请求会去这个线程池中拿一个线程去处理,demo2发生请求也会去这个线程池中取,这样假设demo1的扇出链路发生问题导致这个线程池线程被取光,这时候demo2发生请求后由于没有线程可用就在这等待,超过时间后,demo2出现熔断,但这种熔断不是因为demo2的扇出链路出问题导致的,而是由于demo1引起的,这样就出现了服务之间没有一个线程池隔离导致的熔断,那么hystrix就出现了舱壁模式来进行这个保护,让demo1出现问题不会影响demo2
如下图很好的说明这个问题
在没有使用舱壁来保户船时,船体出现一个洞口,整个船舱都会进水导致整个船遭殃,
而使用舱壁模式时,如果船出现一个洞口只会有一个船舱进水,不会沉船
如下为代码体现
@RequestMapping("/demo1/{userId}")
@HystrixCommand(
threadPoolKey = "demo1", //线程池名称
threadPoolProperties = {
@HystrixProperty(name = "coreSize",value = "1"), //线程池的线程数量
@HystrixProperty(name = "maxQueueSize",value = "20") //等待队列长度
},
commandProperties = {
//2秒后调用还未返回就熔断
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",
value = "2000")
}
)
public String demo(@PathVariable Integer userId){
String url = "http://andy-provide/demo/"+userId;
return restTemplate.getForObject(url, String.class);
}
@RequestMapping("/demo2/{userId}")
@HystrixCommand(
threadPoolKey = "demo2", //线程池名称
threadPoolProperties = {
@HystrixProperty(name = "coreSize",value = "1"), //线程池的线程数量
@HystrixProperty(name = "maxQueueSize",value = "20") //等待队列长度
},
//2秒后调用还未返回就熔断
commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",
value = "2000")
}
)
public String demo1(@PathVariable Integer userId){
String url = "http://andy-provide/demo1/"+userId;
return restTemplate.getForObject(url, String.class);
}
更多分享请关注微信公众号