@EnableCircuitBreaker注解
使用@EnableCircuitBreaker注解开启断路器功能,另外@SpringCloudApplication注解也包含@EnableCircuitBreaker注解,以下为@SpringCloudApplication注解的源码
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public @interface SpringCloudApplication {
}
引入Spring Cloud Hystrix
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
方法一:实现HystrixCommand
public class HelloHystrix extends HystrixCommand{
@Autowired
RestTemplate restTemplate;
protected HelloHystrix(String threadKeyName, int timeout, int queueSize, int coreSize) {
super(Setter.withGroupKey(
//设置命令组
HystrixCommandGroupKey.Factory.asKey("springHealthGrooup"))
//设置命令键
.andCommandKey(HystrixCommandKey.Factory.asKey("interventionKey"))
//设置线程池键
.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(threadKeyName))
//设置命令属性
.andCommandPropertiesDefaults(
HystrixCommandProperties.Setter()
.withExecutionTimeoutInMilliseconds(timeout)
)
.andThreadPoolPropertiesDefaults(
HystrixThreadPoolProperties.Setter()
.withMaxQueueSize(queueSize)
.withCoreSize(coreSize)
)
);
}
@Override
protected String run() throws Exception {
return restTemplate.getForEntity("http://provider/hello",String.class).getBody();
}
}
上述代码中的 HystrixCommandGroupKey 和 HystrixCommandKey 分别用来配置服务分组名称和服务名称,然后 HystrixThreadPoolKey 用来配置线程池的名称。
可以使用同步或异步的方式进行调用
//同步执行
Object result = new HelloHystrix("hystrix-thread", 5000, 5, 2).execute();
//异步执行
Future future = new HelloHystrix("hystrix-thread", 5000, 5, 2).queue();
除了传统的同步执行与异步执行之外, 我们还可以将 通过Observable 来实现响应式执行方式。
Observable ho = new HelloHystrix("hystrix-thread", 5000, 5, 2).observe();
Observable co = new HelloHystrix("hystrix-thread", 5000, 5, 2).toObservable();
observe ()和toObservable ()虽然都返回了 Observable, 但是它们略有不同,前者返回的是一个 Hot Observable, 该命令会在 observe ()调用的时候立即执行, 当Observable 每次被订阅的时候会重放它的行为;而后者返回的是 一个 Cold Observable, toObservable ()执行之后,命令不会被立即执行,只有当所有订阅者都订阅它之后才会执行。
方法二:使用@HystrixCommand注解
@HystrixCommand源码如下:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface HystrixCommand {
/**
* The command group key is used for grouping together commands such as for reporting,
* alerting, dashboards or team/library ownership.
* <p/>
* default => the runtime class name of annotated method
*
* @return group key
*/
String groupKey() default "";
/**
* Hystrix command key.
* <p/>
* default => the name of annotated method. for example:
* <code>
* ...
* @HystrixCommand
* public User getUserById(...)
* ...
* the command name will be: 'getUserById'
* </code>
*
* @return command key
*/
String commandKey() default "";
/**
* The thread-pool key is used to represent a
* HystrixThreadPool for monitoring, metrics publishing, caching and other such uses.
*
* @return thread pool key
*/
String threadPoolKey() default "";
/**
* Specifies a method to process fallback logic.
* A fallback method should be defined in the same class where is HystrixCommand.
* Also a fallback method should have same signature to a method which was invoked as hystrix command.
* for example:
* <code>
* @HystrixCommand(fallbackMethod = "getByIdFallback")
* public String getById(String id) {...}
*
* private String getByIdFallback(String id) {...}
* </code>
* Also a fallback method can be annotated with {@link HystrixCommand}
* <p/>
* default => see {@link com.netflix.hystrix.contrib.javanica.command.GenericCommand#getFallback()}
*
* @return method name
*/
String fallbackMethod() default "";
/**
* Specifies command properties.
*
* @return command properties
*/
HystrixProperty[] commandProperties() default {};
/**
* Specifies thread pool properties.
*
* @return thread pool properties
*/
HystrixProperty[] threadPoolProperties() default {};
/**
* Defines exceptions which should be ignored.
* Optionally these can be wrapped in HystrixRuntimeException if raiseHystrixExceptions contains RUNTIME_EXCEPTION.
*
* @return exceptions to ignore
*/
Class<? extends Throwable>[] ignoreExceptions() default {};
/**
* Specifies the mode that should be used to execute hystrix observable command.
* For more information see {@link ObservableExecutionMode}.
*
* @return observable execution mode
*/
ObservableExecutionMode observableExecutionMode() default ObservableExecutionMode.EAGER;
/**
* When includes RUNTIME_EXCEPTION, any exceptions that are not ignored are wrapped in HystrixRuntimeException.
*
* @return exceptions to wrap
*/
HystrixException[] raiseHystrixExceptions() default {};
/**
* Specifies default fallback method for the command. If both {@link #fallbackMethod} and {@link #defaultFallback}
* methods are specified then specific one is used.
* note: default fallback method cannot have parameters, return type should be compatible with command return type.
*
* @return the name of default fallback method
*/
String defaultFallback() default "";
}
示例:
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(threadPoolKey = "hystrixTest",
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "2"),
@HystrixProperty(name = "maxQueueSize", value = "10")
},
fallbackMethod = "helloFallback")
public String helloService() {
return restTemplate.getForEntity("http://provider/hello", String.class).getBody();
}
public String helloFallback() {
return "error";
}
}
@HystrixCommand用于指定一些应该作为 hystrix 命令处理的方法。该注解中的fallbackMethod属性用于指定熔断时的回调函数,用来实现服务的降级处理逻辑。
当provider服务不可用时,就会触发断路器,然后直接调用回调函数helloFallback函数
@HystrixCommand还提供了
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "12000"),
//一个滑动窗口内最小的请求数
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
//错误比率阈值
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "75"),
//触发熔断的时间值
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "7000"),
//一个滑动窗口的时间长度
@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "15000"),
//一个滑动窗口被划分的数量
@HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "5") })
hystrix实现原理可参考:
Hystrix实现原理_skh2015java的博客-优快云博客
https://skaygo.blog.youkuaiyun.com/article/details/120750565
378



被折叠的 条评论
为什么被折叠?



