先介绍下流程把:
如果用户发了很多请求,并且调用的时候失败很多次,达到了熔断的条件,那么就会触发熔断,让降级逻辑变为主逻辑,所以在熔断的时候,就算你此次调用会成功,也会触发降级逻辑。过了一定的时间,状态会变为半开,此次如果有请求被正确调用,那么熔断就直接关闭了。如果此次请求还是不成功,那么再次变为熔断状态,过一会儿再半开,这样循环。
下面展示下代码:
package van.client.controller;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import van.client.feign.FClient;
import javax.annotation.Resource;
/**
* @author Van
* @date 2020/4/11 - 10:24
*/
@DefaultProperties(defaultFallback = "defaultFallBack")
@RestController
@RequestMapping("/feign")
public class FeignController {
@Resource
private FClient fClient;
//专门给这个method设置的降级操作
// @HystrixCommand(fallbackMethod = "fallback")
//设置服务超时,默认是1s,这里设置为了3s,意思:如果3s内还没有调用成功这个服务,那么就进行降级,触发fallback函数
// @HystrixCommand(commandProperties = {
// @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")//设置超时时间为3s
// })
//熔断机制
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),
})
@RequestMapping("/msg")
public String msg(){
return fClient.msg();
}
private String fallback(){
return "i'am busy!!!!!";
}
private String defaultFallBack(){
return "this is default fall back";
}
}
介绍下用到的参数:
另外:如果不想在注解中写入这写配置信息的话,还可以写在配置文件中:
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=2000
hystrix.command.methodName.execution.isolation.thread.timeoutInMilliseconds=2000
如果要单独给一个method设置超时:就得用下面的这个了,写上method的名字。因为:
它这里默认就是该方法的名字。
这篇介绍的挺全很nice