一、启动类添加注解
package com.ssm.sku;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@MapperScan(value = "com.ssm.*.mapper")
@ComponentScan(value = "com.ssm")
@EnableHystrix
public class SkuApplication {
public static void main(String[] args) {
System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
SpringApplication.run(SkuApplication.class, args);
}
}
二、提供方降级
@GetMapping("testHystrixTimeOut")
@HystrixCommand(fallbackMethod = "testHystrixTimeoutHandler", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
})
public String testHystrixTimeOut() throws InterruptedException {
Thread.sleep(5000);
return "Hello hystrix timeOut!";
}
public String testHystrixTimeoutHandler() {
return "我降级了!!!";
}
参数解读:
-
@HystrixCommand 声明该方法为是一个hystrix命令
-
fallbackMethod 属性提供回退方法, 当方法执行失败时调用(如超时、异常等)
-
commandProperties 属性可指定Hystrix命令的多个配置属性
-
@HystrixProperty 每个配置都通过 @HystrixProperty 注解来定义,其中 name 属性指定了配置的名称,value 属性指定了配置的值
-
execution.isolation.thread.timeoutInMilliseconds 隔离线程的超时,单位为毫秒。超过指定时间会调用回退方法
结果:
三、调用方降级
将sku微服务模块中的方法写到home微服务模块的feign中并在controller中提供方法调用
feign新增:
@GetMapping("testHystrix")
public String testHystrix();
@GetMapping("testHystrixTimeOut")
public String testHystrixTimeOut();
controller新增:
@GetMapping("getHystrixTimeOut")
@HystrixCommand(fallbackMethod = "testHystrixTimeoutHandler", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
})
public String testHystrixTimeOut() {
return skuFeignService.testHystrixTimeOut();
}
public String testHystrixTimeoutHandler() {
return "主动降级了!!";
}
启动类添加@EnableHystrix注解
结果: