io.vavr.control.Try.run()方法的使用及代码示例

x33g5p2x  于2022-01-30 转载在 其他  
字(15.6k)|赞(0)|评价(0)|浏览(419)

本文整理了Java中io.vavr.control.Try.run()方法的一些代码示例,展示了Try.run()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Try.run()方法的具体详情如下:
包路径:io.vavr.control.Try
类名称:Try
方法名:run

Try.run介绍

[英]Creates a Try of a CheckedRunnable.
[中]创建CheckedRunnable的尝试。

代码示例

代码示例来源:origin: vavr-io/vavr

/**
 * Creates a Try of a Runnable.
 *
 * @param runnable A runnable
 * @return {@code Success(null)} if no exception occurs, otherwise {@code Failure(throwable)} if an exception occurs
 * calling {@code runnable.run()}.
 */
static Try<Void> runRunnable(Runnable runnable) {
  Objects.requireNonNull(runnable, "runnable is null");
  return run(runnable::run);
}

代码示例来源:origin: vavr-io/vavr

/**
 * Transforms the value of this {@code Future}, whether it is a success or a failure.
 *
 * @param f   A transformation
 * @param <U> Generic type of transformation {@code Try} result
 * @return A {@code Future} of type {@code U}
 * @throws NullPointerException if {@code f} is null
 */
default <U> Future<U> transformValue(Function<? super Try<T>, ? extends Try<? extends U>> f) {
  Objects.requireNonNull(f, "f is null");
  return run(executor(), complete ->
    onComplete(t -> Try.run(() -> complete.with(f.apply(t)))
        .onFailure(x -> complete.with(Try.failure(x)))
    )
  );
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldDecorateConsumerAndReturnWithException() throws Throwable {
  // Given
  Bulkhead bulkhead = Bulkhead.of("test", config);
  // When
  Consumer<String> consumer = Bulkhead.decorateConsumer(bulkhead, (value) -> {throw new RuntimeException("BAM!");});
  Try<Void> result = Try.run(() -> consumer.accept("Tom"));
  // Then
  assertThat(result.isFailure()).isTrue();
  assertThat(result.failed().get()).isInstanceOf(RuntimeException.class);
  assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldDecorateCheckedRunnableAndReturnWithException() throws Throwable {
  // Given
  Bulkhead bulkhead = Bulkhead.of("test", config);
  // When
  CheckedRunnable checkedRunnable = Bulkhead.decorateCheckedRunnable(bulkhead, () -> {throw new RuntimeException("BAM!");});
  Try<Void> result = Try.run(checkedRunnable);
  // Then
  assertThat(result.isFailure()).isTrue();
  assertThat(result.failed().get()).isInstanceOf(RuntimeException.class);
  assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldDecorateRunnableAndReturnWithException() throws Throwable {
 
  // Given
  Bulkhead bulkhead = Bulkhead.of("test", config);
  // When
  Runnable runnable = Bulkhead.decorateRunnable(bulkhead, () -> {throw new RuntimeException("BAM!");});
  Try<Void> result = Try.run(runnable::run);
  //Then
  assertThat(result.isFailure()).isTrue();
  assertThat(result.failed().get()).isInstanceOf(RuntimeException.class);
  assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void decorateCheckedRunnable() throws Throwable {
  CheckedRunnable runnable = mock(CheckedRunnable.class);
  CheckedRunnable decorated = RateLimiter.decorateCheckedRunnable(limit, runnable);
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(false);
  Try decoratedRunnableResult = Try.run(decorated);
  then(decoratedRunnableResult.isFailure()).isTrue();
  then(decoratedRunnableResult.getCause()).isInstanceOf(RequestNotPermitted.class);
  verify(runnable, never()).run();
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(true);
  Try secondRunnableResult = Try.run(decorated);
  then(secondRunnableResult.isSuccess()).isTrue();
  verify(runnable, times(1)).run();
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldDecorateCheckedConsumerAndReturnWithException() throws Throwable {
  // Given
  Bulkhead bulkhead = Bulkhead.of("test", config);
  // When
  CheckedConsumer<String> checkedConsumer = Bulkhead.decorateCheckedConsumer(bulkhead, (value) -> {
    throw new RuntimeException("BAM!");
  });
  Try<Void> result = Try.run(() -> checkedConsumer.accept("Tom"));
  // Then
  assertThat(result.isFailure()).isTrue();
  assertThat(result.failed().get()).isInstanceOf(RuntimeException.class);
  assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldDecorateConsumerAndReturnWithException() throws Throwable {
  // Given
  CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();
  CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("testName");
  CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
  assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0);
  //When
  Consumer<String> consumer = CircuitBreaker.decorateConsumer(circuitBreaker, (value) -> {
    throw new RuntimeException("BAM!");
  });
  //Then
  Try<Void> result = Try.run(() -> consumer.accept("Tom"));
  assertThat(result.isFailure()).isTrue();
  assertThat(result.failed().get()).isInstanceOf(RuntimeException.class);
  assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
  assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1);
  assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(0);
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldDecorateCheckedRunnableAndReturnWithException() throws Throwable {
  // Given
  CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();
  CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("testName");
  CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
  assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0);
  //When
  CheckedRunnable checkedRunnable = CircuitBreaker.decorateCheckedRunnable(circuitBreaker, () -> {
    throw new RuntimeException("BAM!");
  });
  //Then
  Try<Void> result = Try.run(checkedRunnable);
  assertThat(result.isFailure()).isTrue();
  assertThat(result.failed().get()).isInstanceOf(RuntimeException.class);
  assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
  assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1);
  assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(0);
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldDecorateRunnableAndReturnWithException() throws Throwable {
  // Given
  CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();
  CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("testName");
  CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
  assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0);
  //When
  Runnable runnable = CircuitBreaker.decorateRunnable(circuitBreaker, () -> {
    throw new RuntimeException("BAM!");
  });
  //Then
  Try<Void> result = Try.run(runnable::run);
  assertThat(result.isFailure()).isTrue();
  assertThat(result.failed().get()).isInstanceOf(RuntimeException.class);
  assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
  assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1);
  assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(0);
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldReturnFailureWithRuntimeException() {
  // Given
  CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName");
  assertThat(circuitBreaker.getState()).isEqualTo(CircuitBreaker.State.CLOSED);
  CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
  assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0);
  assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(0);
  //When
  CheckedRunnable checkedRunnable = CircuitBreaker.decorateCheckedRunnable(circuitBreaker, () -> {
    throw new RuntimeException("BAM!");
  });
  Try result = Try.run(checkedRunnable);
  //Then
  assertThat(result.isFailure()).isTrue();
  assertThat(result.failed().get()).isInstanceOf(RuntimeException.class);
  assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
  assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1);
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldDecorateCheckedConsumerAndReturnWithException() throws Throwable {
  // Given
  CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();
  CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("testName");
  CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
  assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0);
  //When
  CheckedConsumer<String> checkedConsumer = CircuitBreaker.decorateCheckedConsumer(circuitBreaker, (value) -> {
    throw new RuntimeException("BAM!");
  });
  //Then
  Try<Void> result = Try.run(() -> checkedConsumer.accept("Tom"));
  assertThat(result.isFailure()).isTrue();
  assertThat(result.failed().get()).isInstanceOf(RuntimeException.class);
  assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
  assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1);
  assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(0);
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldReturnFailureWithRuntimeException() {
  // Given
  BulkheadConfig config = BulkheadConfig.custom().maxConcurrentCalls(2).build();
  Bulkhead bulkhead = Bulkhead.of("test", config);
  bulkhead.isCallPermitted();
  //v When
  CheckedRunnable checkedRunnable = Bulkhead.decorateCheckedRunnable(bulkhead, () -> {throw new RuntimeException("BAM!");});
  Try result = Try.run(checkedRunnable);
  //Then
  assertThat(result.isFailure()).isTrue();
  assertThat(result.failed().get()).isInstanceOf(RuntimeException.class);
  assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldReturnAfterThreeAttempts() {
  // Given the HelloWorldService throws an exception
  BDDMockito.willThrow(new WebServiceException("BAM!")).given(helloWorldService).sayHelloWorld();
  // Create a Retry with default configuration
  Retry retry = Retry.ofDefaults("id");
  // Decorate the invocation of the HelloWorldService
  CheckedRunnable retryableRunnable = Retry.decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld);
  // When
  Try<Void> result = Try.run(retryableRunnable);
  // Then the helloWorldService should be invoked 3 times
  BDDMockito.then(helloWorldService).should(Mockito.times(3)).sayHelloWorld();
  // and the result should be a failure
  Assertions.assertThat(result.isFailure()).isTrue();
  // and the returned exception should be of type RuntimeException
  Assertions.assertThat(result.failed().get()).isInstanceOf(WebServiceException.class);
  Assertions.assertThat(sleptTime).isEqualTo(RetryConfig.DEFAULT_WAIT_DURATION*2);
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void testDecorateRunnable() {
  // Given the HelloWorldService throws an exception
  BDDMockito.willThrow(new WebServiceException("BAM!")).given(helloWorldService).sayHelloWorld();
  // Create a Retry with default configuration
  Retry retry = Retry.ofDefaults("id");
  // Decorate the invocation of the HelloWorldService
  Runnable runnable = Retry.decorateRunnable(retry, helloWorldService::sayHelloWorld);
  // When
  Try<Void> result = Try.run(runnable::run);
  // Then the helloWorldService should be invoked 3 times
  BDDMockito.then(helloWorldService).should(Mockito.times(3)).sayHelloWorld();
  // and the result should be a failure
  Assertions.assertThat(result.isFailure()).isTrue();
  // and the returned exception should be of type RuntimeException
  Assertions.assertThat(result.failed().get()).isInstanceOf(WebServiceException.class);
  Assertions.assertThat(sleptTime).isEqualTo(RetryConfig.DEFAULT_WAIT_DURATION*2);
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldReturnFailureWithBulkheadFullException() {
  // tag::bulkheadFullException[]
  // Given
  BulkheadConfig config = BulkheadConfig.custom().maxConcurrentCalls(2).build();
  Bulkhead bulkhead = Bulkhead.of("test", config);
  bulkhead.isCallPermitted();
  bulkhead.isCallPermitted();
  // When
  CheckedRunnable checkedRunnable = Bulkhead.decorateCheckedRunnable(bulkhead, () -> {throw new RuntimeException("BAM!");});
  Try result = Try.run(checkedRunnable);
  //Then
  assertThat(result.isFailure()).isTrue();
  assertThat(result.failed().get()).isInstanceOf(BulkheadFullException.class);
  // end::bulkheadFullException[]
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldReturnAfterOneAttempt() {
  // Given the HelloWorldService throws an exception
  BDDMockito.willThrow(new WebServiceException("BAM!")).given(helloWorldService).sayHelloWorld();
  // Create a Retry with default configuration
  RetryConfig config = RetryConfig.custom().maxAttempts(1).build();
  Retry retry = Retry.of("id", config);
  // Decorate the invocation of the HelloWorldService
  CheckedRunnable retryableRunnable = Retry.decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld);
  // When
  Try<Void> result = Try.run(retryableRunnable);
  // Then the helloWorldService should be invoked 1 time
  BDDMockito.then(helloWorldService).should(Mockito.times(1)).sayHelloWorld();
  // and the result should be a failure
  Assertions.assertThat(result.isFailure()).isTrue();
  // and the returned exception should be of type RuntimeException
  Assertions.assertThat(result.failed().get()).isInstanceOf(WebServiceException.class);
  Assertions.assertThat(sleptTime).isEqualTo(0);
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void testDecorateCheckedRunnable() throws IOException {
  CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
  CheckedRunnable decoratedRunnable = Decorators.ofCheckedRunnable(() -> helloWorldService.sayHelloWorldWithException())
    .withCircuitBreaker(circuitBreaker)
    .withRetry(Retry.ofDefaults("id"))
    .withRateLimiter(RateLimiter.ofDefaults("testName"))
    .withBulkhead(Bulkhead.ofDefaults("testName"))
    .decorate();
  Try.run(decoratedRunnable);
  CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
  assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
  assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1);
  // Then the helloWorldService should be invoked 1 time
  BDDMockito.then(helloWorldService).should(times(1)).sayHelloWorldWithException();
}

代码示例来源:origin: resilience4j/resilience4j

@Test
  public void shouldTakeIntoAccountBackoffFunction() {
    // Given the HelloWorldService throws an exception
    BDDMockito.willThrow(new WebServiceException("BAM!")).given(helloWorldService).sayHelloWorld();

    // Create a Retry with a backoff function squaring the interval
    RetryConfig config = RetryConfig
        .custom()
        .intervalFunction(IntervalFunction.of(Duration.ofMillis(500), x -> x * x))
        .build();

    Retry retry = Retry.of("id", config);
    // Decorate the invocation of the HelloWorldService
    CheckedRunnable retryableRunnable = Retry.decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld);

    // When
    Try<Void> result = Try.run(retryableRunnable);

    // Then the slept time should be according to the backoff function
    BDDMockito.then(helloWorldService).should(Mockito.times(3)).sayHelloWorld();
    Assertions.assertThat(sleptTime).isEqualTo(
        RetryConfig.DEFAULT_WAIT_DURATION +
            RetryConfig.DEFAULT_WAIT_DURATION*RetryConfig.DEFAULT_WAIT_DURATION);
  }
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldReturnAfterTwoAttempts() {
  // Given the HelloWorldService throws an exception
  BDDMockito.willThrow(new WebServiceException("BAM!")).willDoNothing().given(helloWorldService).sayHelloWorld();
  // Create a Retry with default configuration
  Retry retry = Retry.ofDefaults("id");
  TestSubscriber<RetryEvent.Type> testSubscriber = toFlowable(retry.getEventPublisher())
      .map(RetryEvent::getEventType)
      .test();
  // Decorate the invocation of the HelloWorldService
  CheckedRunnable retryableRunnable = Retry.decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld);
  // When
  Try<Void> result = Try.run(retryableRunnable);
  // Then the helloWorldService should be invoked 2 times
  BDDMockito.then(helloWorldService).should(Mockito.times(2)).sayHelloWorld();
  // and the result should be a sucess
  Assertions.assertThat(result.isSuccess()).isTrue();
  Assertions.assertThat(sleptTime).isEqualTo(RetryConfig.DEFAULT_WAIT_DURATION);
  testSubscriber.assertValueCount(2).assertValues(RetryEvent.Type.RETRY, RetryEvent.Type.SUCCESS);
}

相关文章