public class CustomerCommand extends HystrixCommand<Object> {
private RestTemplate restTemplate;
public CustomerCommand(RestTemplate restTemplate) {
super(
Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("study-hystrix"))
.andCommandKey(HystrixCommandKey.Factory.asKey("CustomerController"))
.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("studyThreadPool"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionTimeoutInMilliseconds(100).withCircuitBreakerSleepWindowInMilliseconds(5000))
.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
.withCoreSize(1)
.withMaxQueueSize(2))
);
this.restTemplate = restTemplate;
}
@Override
protected Object run() throws Exception {
//调用我们期望调用的方法
System.out.println("当前线程是:"+Thread.currentThread().getName());
return restTemplate.getForObject("http://HELLOSERVER/index",String.class);
}
@Override
protected Object getFallback() {
System.out.println("服务降级了");
return "服务降级了";
}
}
@SpringBootApplication
@EnableEurekaClient
@RestController
public class SpringCloudHystrixApplication {
@Autowired
private RestTemplate restTemplate;
@Autowired
private LoadBalancerClient loadBalancerClient;
public static void main(String[] args) {
SpringApplication.run(SpringCloudHystrixApplication.class, args);
}
@GetMapping("index")
public Object index(){
return new CustomerCommand(restTemplate).execute();
}
@HystrixCommand(fallbackMethod = "callTimeOutFallback",
threadPoolProperties = {@HystrixProperty(name = "coreSize",value = "1"),
@HystrixProperty(name = "queueSizeRejectionThreshold",value = "1"),
},
commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "100")})
@GetMapping("index2")
public Object index2(){
return restTemplate.getForObject("http://HELLOSERVER/index",String.class);
}
public Object callTimeOutFallback(){
return "请求index2降级";
}
}
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>