接上一章节Hystrix 的服务降级与异常处理,这里讲讲自定义 Hystrix 请求的服务熔断处理、同步与异步调用、 请求异常熔断处理
自定义类继承自 HystrixCommand 来实现自定义的 Hystrix 请求,在 getFallback 方法中调用 getExecutionException 方法来获取服务抛出的异常;而不是使用注解的方式
import com.netflix.hystrix.HystrixCommand;
import org.springframework.web.client.RestTemplate;/*** 自定义的Hystrix请求*/
//HystrixCommand泛型类 由于我们服务提供者返回值是String类型 所以定义为String类型
public class HystrixCommandUtil extends HystrixCommand {private RestTemplate restTemplate;//构造方法 赋值给this.restTemplate成员变量public HystrixCommandUtil (Setter setter,RestTemplate restTemplate){super(setter);this.restTemplate=restTemplate;}@Overrideprotected String run() throws Exception {//调用远程服务return restTemplate.getForEntity("http://SPRINGCLOUD-SERVICE-PROVIDER/service/provide", String.class).getBody();}/*** 当远程服务超时,异常,不可用的情况时;会触发该熔断方法* @return*/@Overridepublic String getFallback(){//实现服务熔断/降级逻辑return "error";}
}
@RequestMapping(value = "/web/hystrix/command")public String hystrixCommandController() {HystrixCommandUtil hystrixCommandUtil=new HystrixCommandUtil(com.netflix.hystrix.HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("")),restTemplate);return hystrixCommandUtil.execute();}
@RequestMapping(value = "/web/hystrix/command")public String hystrixCommandController() throws ExecutionException, InterruptedException {HystrixCommandUtil hystrixCommandUtil=new HystrixCommandUtil(com.netflix.hystrix.HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("")),restTemplate);//同步调用(该方法执行后,会等待远程的返同结果,拿到了远程的返同结果,该方法才返回,然后代码继续往下执行)//String str=hystrixCommandUtil.execute();//异步调用(该方法执行后,不会马上有远程的的返回结果,将来会有结果)Future future=hystrixCommandUtil.queue();//写一下业务逻辑处理,提高系统性能//阻塞的方法,直到拿到结果String str=future.get();return str;}