hystrix简单使用――fallback

匿名 (未验证) 提交于 2019-12-03 00:33:02

本文主要介绍fallback,目的是能够在程序中看到fallback的处理。

主要参考:

官网上的原话是这么说的

现在实现一个默认就是出错的然后看效果是什么样子的。正常应该直接执行getFallback()里面的内容。

1、添加maven依赖

<!-- https://mvnrepository.com/artifact/com.netflix.hystrix/hystrix-core -->         <dependency>             <groupId>com.netflix.hystrix</groupId>             <artifactId>hystrix-core</artifactId>             <version>1.5.12</version>         </dependency>

2、创建一个继承hystrixCommand的类

package com.xueyou.hystrixdemo.v2;  import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey;   public class CommandHelloworldWithFallBack extends HystrixCommand<String> {     private String name;      public CommandHelloworldWithFallBack(HystrixCommandGroupKey group, String name) {         super(group);         this.name = name;     }      @Override     protected String getFallback() {         return "fall back " + name;     }      @Override     protected String run() {         throw new RuntimeException("this command always fails");     } } 

3、添加测试类进行测试

package com.xueyou.hystrixdemo.v2;  import com.netflix.hystrix.HystrixCommandGroupKey;  public class HelloWorldFallBack {     public static void main(String[] args) {         String result = new CommandHelloworldWithFallBack(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"), "aaabbbccc").execute();         String result2 = new CommandHelloworldWithFallBack(HystrixCommandGroupKey.Factory.asKey("ExampleGroup2"), "123sss").execute();         System.out.println(result);         System.out.println(result2);     } } 

4、运行结果:



根据官网上的解释,每次执行run()方法的时候都会出现异常,但是这里没有返回异常,而是通过执行getFallback()方法然后返回getFallback()的返回值即可。
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!