hystrix简单使用——fallback

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

主要参考:

官网上的原话是这么说的
Hystrix will execute this fallback for all types of failure such as run() failure, timeout, thread pool or semaphore rejection, and circuit-breaker short-circuiting.

现在实现一个默认就是出错的然后看效果是什么样子的。正常应该直接执行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()的返回值即可。

猜你喜欢

转载自blog.csdn.net/wild46cat/article/details/80781687
今日推荐