如何强制 Hystrix 断路器打开?

How to force a Hystrix circuit breaker open?

我想以编程方式强制断路器为特定组打开。我想我可以通过在组中的命令上设置配置以强制打开,然后 运行 该命令来做到这一点。但是,这似乎不起作用。这可能吗?我应该采取不同的方法吗?这是我在第二次 assertEquals 调用时失败的测试。

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class ForceCircuitBreakerCommandTest {

    @Test
    public void testForceOpen(){

        assertEquals(Boolean.TRUE, new FakeCommand().execute());

        new OpenCircuitBreakerCommand().execute();

        assertEquals(Boolean.FALSE, new FakeCommand().execute());

    }

    private class FakeCommand extends HystrixCommand<Boolean> {

        public FakeCommand(){
            super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestGroup")));
        }

        @Override
        public Boolean run(){return Boolean.TRUE;}

        @Override
        public Boolean getFallback() {return Boolean.FALSE;}
    }

    private class OpenCircuitBreakerCommand extends HystrixCommand<Boolean> {

        public OpenCircuitBreakerCommand(){
            super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestGroup"))
                    .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                                    .withCircuitBreakerForceOpen(true)));
        }

        @Override
        public Boolean run(){return Boolean.TRUE;}

        @Override
        public Boolean getFallback() {return Boolean.FALSE;}
    }
}

我已经使用

设置了自定义属性,例如 "hystrix.command.HystrixCommandKey.circuitBreaker.forceOpen"
import com.netflix.config.ConfigurationManager;

ConfigurationManager.getConfigInstance()
    .setProperty("hystrix.command.HystrixCommandKey.circuitBreaker.forceOpen",
    true);

ConfigurationManager是内部使用的Archaius实例。

您不一定非要使用 ConfigurationManager。该测试需要说:

@Test
public void testForceOpen() {
    assertEquals(Boolean.TRUE, new FakeCommand().execute());
    assertEquals(Boolean.FALSE, new OpenCircuitBreakerCommand().execute());
}

这是使用 Senthilkumar Gopal 的答案对测试进行的编辑

@Test
public void testForceOpen() {

    assertEquals(Boolean.TRUE, new OpenCircuitBreakerCommand().execute());

    ConfigurationManager.getConfigInstance()
            .setProperty("hystrix.command.OpenCircuitBreakerCommand.circuitBreaker.forceOpen",
                    true);

    assertEquals(Boolean.FALSE, new OpenCircuitBreakerCommand().execute());
}