世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。
Java API的形式:
public class CustomCommand extends HystrixCommand<Object> {
protected CustomCommand () {
super(
Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("group1"))
.andCommandKey(HystrixCommandKey.Factory.asKey("CustomController"))
.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("customThreadPool"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withCircuitBreakerSleepWindowInMilliseconds(5000))
.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
.withCoreSize(1)
.withMaxQueueSize(200))
);
}
@Override
protected Object run() throws Exception {
throw new RuntimeException();
//return "controller调用";
}
@Override
protected Object getFallback() {
return "降级了";
}
}
使用:
@RestController
public class CustomController {
@GetMapping("/hystrix")
public Object hystrix () {
return new CustomCommand().execute();
}
}
注解形式:
首先要在启动类中加@EnableHystrix注解
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class Client1Application {
public static void main(String[] args) {
SpringApplication.run(Client1Application.class, args);
}
}
使用:
@GetMapping("/hystrix2")
@HystrixCommand(fallbackMethod = "exceptionFallBack",
threadPoolKey = "customThreadPool2",
threadPoolProperties = {
@HystrixProperty(name="coreSize", value="1"),
},
commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="100")
})
public Object hystrix2 () throws InterruptedException {
System.out.println("当前线程:" + Thread.currentThread().getName());
//return "hystrix2Controller";
throw new RuntimeException();
}
public Object exceptionFallBack () {
return "降级了2";
}