首页 > 解决方案 > Hystrix:如何封装多路呼叫

问题描述

我正在使用 Hystrix 来改进我的服务。如何将服务调用解封装到 Hystrix 中。我知道你可以为每个调用创建一个特殊的 hystrix 类,但是如果不使用 Spring,这将是太多的工作!

我尝试用伪代码描述我的问题:

public class HystrixController extends HystrixCommand {


    public static void main(String[] args) throws Exception {
        HystrixController hystrixController = new HystrixController();
        System.out.print(hystrixController.execute());

    }

    private final ExampleService exampleService;

    protected HystrixController() throws Exception {
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
        this.exampleService = new ExampleService();
    }

    // Call 1
    public List getItemsAsList() {
        return exampleService.getItemsByContractId(contractID);
    }

    // Call 2
    public List getItemsByName() {
        return exampleService.getItemsByName(contractID);
    }

    // How can I isolate the two calls ? The run() only allows me to use one.
    @Override
    protected List run() throws Exception {
        return getItemsAsList();
    }

}

在示例中,您可以看到只能执行一次调用。我想要这样的东西:

public class HystrixController extends HystrixCommand {


    public static void main(String[] args) throws Exception {
        HystrixController hystrixController = new HystrixController();
        System.out.print(hystrixController.execute(1));
        System.out.print(hystrixController.execute(2));

    }

    private final ExampleService exampleService;

    protected HystrixController() throws Exception {
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
        this.exampleService = new ExampleService();
    }

    // Call 1
    public List getItemsAsList() {
        return exampleService.getItemsByContractId(contractID);
    }

    // Call 2
    public List getItemsByName() {
        return exampleService.getItemsByName(contractID);
    }

    // Multi Threads
    @Override
    protected List run_getItemsAsList() throws Exception {
        return getItemsAsList();
    }
    @Override
    protected List run_getItemsByName() throws Exception {
        return getItemsByName();
    }

}

提前谢谢你,我很抱歉我的英语不好

标签: javajbosshystrixnetflix

解决方案


推荐阅读