先修课:#Hystrix:服务熔断、服务降级 #自定义熔断: @FDDLC
一、自定义HystrixCommand中的异常处理
1、provider:
@RequestMapping("/hystrix")
public String hystrix() throws Exception{
//Thread.sleep(10000);
int i=1/0;
return "I'm from the provider. If you can see me, it means the connection works well.";
}
上面的 int i = 1/0; 会抛出异常!
2、consumer中自定义的HystrixCommand:
package cn.consumer.config;
import com.netflix.hystrix.HystrixCommand;
import org.springframework.web.client.RestTemplate;
//注意:有两个HystrixCommand:一个是注解,一个是抽象类。千万不要导错了包!
public class MyHystrixCommand extends HystrixCommand<String> {
private RestTemplate restTemplate;
public MyHystrixCommand(Setter setter,RestTemplate restTemplate) {
super(setter);
this.restTemplate=restTemplate;
}
@Override
protected String run() throws Exception {
return restTemplate.getForObject("http://provider/hystrix", String.class);
}
@Override
protected String getFallback() {
System.out.println("super.getExecutionException().getMessage():"+super.getExecutionException().getMessage());
return "getFallback()";
}
}
3、consumer中的controller:
//自定义熔断
@RequestMapping("/myhystrix")
public String myhystrix(){
MyHystrixCommand myHystrixCommand=new MyHystrixCommand(
com.netflix.hystrix.HystrixCommand.Setter.withGroupKey(
HystrixCommandGroupKey.Factory.asKey("")
), restTemplate);
return myHystrixCommand.execute();
}
4、请求结果:
5、consumer控制台输出:
二、HystrixCommand的异常调用
1、provider:
@RequestMapping("/hystrix")
public String hystrix() throws Exception{
//Thread.sleep(10000);
//int i=1/0;
return "I'm from the provider. If you can see me, it means the connection works well.";
}
2、consumer中的MyHystrixCommand:
package cn.consumer.config;
import com.netflix.hystrix.HystrixCommand;
import org.springframework.web.client.RestTemplate;
//注意:有两个HystrixCommand:一个是注解,一个是抽象类。千万不要导错了包!
public class MyHystrixCommand extends HystrixCommand<String> {
private RestTemplate restTemplate;
public MyHystrixCommand(Setter setter,RestTemplate restTemplate) {
super(setter);
this.restTemplate=restTemplate;
}
@Override
protected String run() throws Exception {
return restTemplate.getForObject("http://provider/hystrix", String.class);
}
@Override
protected String getFallback() {
System.out.println("super.getExecutionException().getMessage():"+super.getExecutionException().getMessage());
return "getFallback()";
}
}
3、consumer中的controller:
//自定义熔断
@RequestMapping("/myhystrix")
public String myhystrix()throws Exception{
MyHystrixCommand myHystrixCommand=new MyHystrixCommand(
com.netflix.hystrix.HystrixCommand.Setter.withGroupKey(
HystrixCommandGroupKey.Factory.asKey("")
), restTemplate);
Future<String> future = myHystrixCommand.queue(); //异步调用
//可以先处理其他逻辑,之后再去future中拿结果
//有两个get方法:
//V get(long timeout, TimeUnit unit):带参的get方法可以指定超时时间
return future.get(); //无参的get方法
}
核心就是上面的queue和get!
4、请求: