springCloud组件之Hystrix
背景
最近在研究sentinel,但是在sentinel之前,大多数使用的熔断降级肯定还是Hystrix。
hystrix是Netlifx开源的一款容错框架,防雪崩利器,具备服务降级,服务熔断,依赖隔离,监控(Hystrix Dashboard)等功能
雪崩的含义是指微服务调用链因为一个服务故障,导致整个调用链路异常。
接下来使用先加入Maven依赖
注:早期比较流行的是Hystrix框架,但目前国内实用最广泛的还是阿里巴巴的Sentinel框架,两种框架的隔离策略不一致,Hystrix主要以线程池隔离为主,sentinel则以信号量隔离为主,正是因为线程池隔离,则导致了Feign使用会有一系列问题,以下会提供解决方案。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
然后在启动类上加入注解:@EnableCircuitBreaker
SpringBoot使用Hystrix
接口端的使用简单一些。
@ApiOperation("服务降级使用")
@GetMapping("hystrix_demote")
@HystrixCommand(fallbackMethod = "hystrixFallback", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
})
public String hystrixDemote(Integer num) throws InterruptedException {
if (num == 1) {
Thread.sleep(6000);
}
return "方法输出内容" + num;
}
private String hystrixFallback(Integer num) {
return "已经降级了" + num;
}
@HystrixCommand当方法报错的时候自动返回fallbackMethod指定方法的内容,
注意方法的返回与参数应当与接口一致。
Feign使用Hystrix
前言,如果对openFeign使用有问题,或者不会使用的,可以访问我的另外一篇文章:
SpringCloud使用FeignClient
@FeignClient(value = "userService",fallbackFactory = UserFeignFallBackFactory.class)
在原本的Feign的注解中,加入fallbackFactory,指定自己创建的FallBack类。
@Slf4j
@Component
public class UserFeignFallBackFactory implements FallbackFactory<UserFeign> {
@Override
public UserFeign create(Throwable throwable) {
log.error("请求用户中心出错:" + throwable.getMessage());
return new UserFeign() {
@Override
public ResponseVO<RegisterPersonalDto> getUserinfo(Integer regId) {
String message = "获取用户信息失败,服务异常,请联系管理员";
log.error(throwable.getMessage());
log.error(message);
return ResponseUtil.get(1, message, null);
}
};
}
}
FallBack类实现FallbackFactory接口。重写create方法,对接口进行降级处理。
但是加入Hystrix之后,会发现,客户端正常请求服务端也会失败,是因为
feign的hystrix隔离策略原因导致feign调用线程和主线程隔离了官方文档
Feign远程调用设置configuration后,RequestContextHolder.getRequestAttributes()为空的,因为,Hystrix的默认隔离级别(线程池隔离),以下附上解决方案。
package com.***.***.configuration;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariable;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle;
import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier;
import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
import com.netflix.hystrix.strategy.properties.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 此类为解决feign开启hystrix后,客户端的feign配置的服务降级,fallbackFactory,但是一直返回异常的问题
* 原因:feign的hystrix隔离策略原因导致feign调用线程和主线程隔离了(官方文档:https://github.com/Netflix/Hystrix/wiki/Configuration#executionisolationstrategy)。
* Feign远程调用设置configuration后,RequestContextHolder.getRequestAttributes()为空的问题
* 由于getRequestAttributes为空无法设置远调的token,导致一直都在走fallBackFactory
* @author sirwsl
*/
@Component
@Primary
@Slf4j
public class CustomFeignHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
private HystrixConcurrencyStrategy hystrixConcurrencyStrategy;
public CustomFeignHystrixConcurrencyStrategy() {
try {
this.hystrixConcurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy();
if (this.hystrixConcurrencyStrategy instanceof CustomFeignHystrixConcurrencyStrategy) {
return;
}
HystrixCommandExecutionHook commandExecutionHook =
HystrixPlugins.getInstance().getCommandExecutionHook();
HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance().getEventNotifier();
HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance().getMetricsPublisher();
HystrixPropertiesStrategy propertiesStrategy =
HystrixPlugins.getInstance().getPropertiesStrategy();
this.logCurrentStateOfHystrixPlugins(eventNotifier, metricsPublisher, propertiesStrategy);
HystrixPlugins.reset();
HystrixPlugins.getInstance().registerConcurrencyStrategy(this);
HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook);
HystrixPlugins.getInstance().registerEventNotifier(eventNotifier);
HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher);
HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy);
} catch (Exception e) {
log.error("Failed to register Sleuth Hystrix Concurrency Strategy", e);
}
}
private void logCurrentStateOfHystrixPlugins(HystrixEventNotifier eventNotifier,
HystrixMetricsPublisher metricsPublisher, HystrixPropertiesStrategy propertiesStrategy) {
if (log.isDebugEnabled()) {
log.debug("Current Hystrix plugins configuration is [" + "concurrencyStrategy ["
+ this.hystrixConcurrencyStrategy + "]," + "eventNotifier [" + eventNotifier + "]," + "metricPublisher ["
+ metricsPublisher + "]," + "propertiesStrategy [" + propertiesStrategy + "]," + "]");
log.debug("Registering Sleuth Hystrix Concurrency Strategy.");
}
}
/**
* 提供在执行前包装/装饰Callable<T>的机会。
* 这可用于注入其他行为,如复制线程状态(如ThreadLocal)。
* 默认实现
* 无包装的直通。
* 参数:
* callable–通过ThreadPoolExecutor执行的callable<T>
* @param callable
* {@code Callable<T>} to be executed via a {@link ThreadPoolExecutor}
* @return
* @param <T>
*/
@Override
public <T> Callable<T> wrapCallable(Callable<T> callable) {
/**
* Holder类以线程绑定的RequestAttributes对象的形式公开web请求。如果可继承标志设置为true,则当前线程生成的任何子线程都将继承该请求。
* 使用RequestContextListener或org.springframework.web.filter。RequestContextFilter以公开当前web请求
* **********!!!!getRequestAttributes()`方法,相当于直接获取ThreadLocal里面的值
*/
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
SecurityContext securityContext = SecurityContextHolder.getContext();
log.info(securityContext.getAuthentication().getDetails().toString());
return new WrappedCallable<>(callable, requestAttributes);
}
/**
*
根据需要提供ThreadPoolExecutor实例的Factory方法。
请注意,如果使用ThreadPoolExecutor更改corePoolSize、maximumPoolSite和keepAliveTime的值,则它们的值将在运行时动态设置。
setCorePoolSize、ThreadPoolExecutor。setMaximumPoolSize和ThreadPoolExecutor。setKeepAliveTime方法。
默认实现
使用标准java.util.concurrent.ThreadPoolExecutor实现
参数:
threadPoolKey–表示此ThreadPoolExecutor将用于的HystrixThreadPool的HystriexThreadpoolKey。
corePoolSize–通过属性请求的核心线程数(如果没有设置属性,则为系统默认值)。
maximumPoolSize–通过属性请求的最大线程数(如果未设置属性,则为系统默认值)。
keepAliveTime–通过属性请求的线程保持活动时间(如果未设置属性,则为系统默认值)。
unit–与keepAliveTime workQueue对应的TimeUnit–由getBlockingQueue(int)提供的Blocking队列<Runnable>
*/
@Override
public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
HystrixProperty<Integer> corePoolSize, HystrixProperty<Integer> maximumPoolSize,
HystrixProperty<Integer> keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
return this.hystrixConcurrencyStrategy.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize, keepAliveTime,
unit, workQueue);
}
@Override
public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
HystrixThreadPoolProperties threadPoolProperties) {
return this.hystrixConcurrencyStrategy.getThreadPool(threadPoolKey, threadPoolProperties);
}
/**
* 工厂方法,提供用于getThreadPool中构造的每个ThreadPoolExecutor的BlockingQueue<Runnable>实例。
* 注意:提供了maxQueueSize值,因此可以使用任何类型的队列,但通常首选不带队列(只是切换)的SynchronousQueue等实现,因为排队是一种反模式,出于延迟容忍的原因,应有意避免。
* 默认实现
* 当maxQueueSize<=0时,实现返回SynchronousQueue;当maxQuueSize>0时,则返回LinkedBlockingQueue。
* 参数:
* maxQueueSize–通过属性请求的队列的最大大小(如果没有设置属性,则为系统默认值)。
* 退货:
* BlockingQueue<Runnable>的实例
* @param maxQueueSize
* The max size of the queue requested via properties (or system default if no properties set).
* @return
*/
@Override
public BlockingQueue<Runnable> getBlockingQueue(int maxQueueSize) {
return this.hystrixConcurrencyStrategy.getBlockingQueue(maxQueueSize);
}
/**
* 方法返回HystrixRequestVariable的实现,该实现的行为类似于ThreadLocal,但其作用域是请求而不是线程。
* 例如,如果请求以HTTP请求开始,以HTTP响应结束,则HystrixRequestVariable应在开始时初始化,可在请求期间生成的任何和所有线程上使用,然后在HTTP请求完成后清除。
* 如果实现了此方法,通常还需要实现wrapCallable(Callable),以便将状态从父线程复制到子线程。
* 参数:
* rv–HystrixRequestVariableLifecycle以及Hystrix的生命周期实施
*/
@Override
public <T> HystrixRequestVariable<T> getRequestVariable(HystrixRequestVariableLifecycle<T> rv) {
return this.hystrixConcurrencyStrategy.getRequestVariable(rv);
}
static class WrappedCallable<T> implements Callable<T> {
private final Callable<T> target;
private final RequestAttributes requestAttributes;
public WrappedCallable(Callable<T> target, RequestAttributes requestAttributes) {
this.target = target;
this.requestAttributes = requestAttributes;
}
/**
* feign打开保险丝(hystrix):feign.hystrix.enabled=true,并使用默认信号隔离级别,
* *HttpServletRequest对象在父线程中相互独立
* *和子线程,并且不共享。
* *因此子线程中使用的父线程的HttpServletRequest数据为空,
* *当然,不可能获得请求头的令牌信息
* *在多线程环境中,在请求之前调用,在调用之前设置上下文
* @return
* @throws Exception
*/
@Override
public T call() throws Exception {
try {
/**
* 将给定的RequestAttributes绑定到当前线程。
* 参数:
* attributes–要公开的RequestAttributes,或为null以重置线程绑定的上下文inheritable–是否将RequestAttribute公开为子线程的可继承属性(使用InheritableThreadLocal)
*/
RequestContextHolder.setRequestAttributes(requestAttributes,true);
return target.call();
} finally {
RequestContextHolder.resetRequestAttributes();
}
}
}
}
完结撒花,下一步Sentinel