Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class RemoteServiceCommand extends HystrixCommand<String> {
- private RemoteService remoteService;
- RemoteServiceCommand(Setter config, RemoteService remoteService) {
- super(config);
- this.remoteService = remoteService;
- }
- @Override
- protected String run() throws Exception {
- return remoteService.execute();
- }
- }
- public class RemoteService {
- static final String SUCCESS = "Success";
- private long wait;
- RemoteService(long wait) {
- this.wait = wait;
- }
- String execute() throws InterruptedException {
- TimeUnit.MILLISECONDS.sleep(wait);
- return SUCCESS;
- }
- }
- public class RemoteServiceTest {
- private static final Logger LOGGER = LoggerFactory.getLogger(RemoteServiceTestCommand.class);
- private static final HystrixCommandGroupKey GROUP_KEY = Factory.asKey("RemoteServiceGroup");
- private HystrixCommand.Setter baseConfig;
- @BeforeEach
- void setUp() {
- baseConfig = HystrixCommand.Setter.withGroupKey(GROUP_KEY);
- }
- @Test
- void testWithTimeoutOf100AndDefaultSettings() {
- var remoteService = new RemoteService(100L);
- assertEquals(SUCCESS, new RemoteServiceCommand(baseConfig, remoteService).execute());
- }
- @Test
- void testWithCircuitBreakerSetup() throws InterruptedException {
- var circuitBreakerProperties = HystrixCommandProperties.Setter()
- .withExecutionTimeoutInMilliseconds(1_000)
- .withCircuitBreakerSleepWindowInMilliseconds(2_000)
- .withExecutionIsolationStrategy(ExecutionIsolationStrategy.THREAD)
- .withCircuitBreakerEnabled(true)
- .withCircuitBreakerRequestVolumeThreshold(1);
- var threadPoolProperties = HystrixThreadPoolProperties.Setter()
- .withMaxQueueSize(1)
- .withCoreSize(1)
- .withQueueSizeRejectionThreshold(1);
- var config = baseConfig
- .andCommandPropertiesDefaults(circuitBreakerProperties)
- .andThreadPoolPropertiesDefaults(threadPoolProperties);
- assertNull(callRemoteService(config, 1_000L));
- assertNull(callRemoteService(config, 1_000L));
- assertNull(callRemoteService(config, 500L));
- TimeUnit.SECONDS.sleep(2L);
- assertEquals(SUCCESS, callRemoteService(config, 500L));
- }
- private String callRemoteService(HystrixCommand.Setter config, long timeout) {
- try {
- return new RemoteServiceCommand(config, new RemoteService(timeout)).execute();
- } catch (HystrixRuntimeException e) {
- var cause = e.getCause();
- if (cause.getMessage() != null) {
- LOGGER.info("{} {}", e.getMessage(), cause.getMessage());
- } else {
- LOGGER.info(e.getMessage());
- }
- return null;
- }
- }
- }
Add Comment
Please, Sign In to add comment