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

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

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

Try.ofSupplier介绍

[英]Creates a Try of a Supplier.
[中]创建一个供应商的尝试。

代码示例

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

  1. @Test
  2. public void shouldDecorateSupplierAndReturnWithException() {
  3. // Given
  4. CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName");
  5. CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
  6. assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0);
  7. // Given the HelloWorldService throws an exception
  8. BDDMockito.given(helloWorldService.returnHelloWorld()).willThrow(new RuntimeException("BAM!"));
  9. //When
  10. Supplier<String> supplier = CircuitBreaker.decorateSupplier(circuitBreaker, helloWorldService::returnHelloWorld);
  11. //Then
  12. Try<String> result = Try.ofSupplier(supplier);
  13. assertThat(result.isFailure()).isTrue();
  14. assertThat(result.failed().get()).isInstanceOf(RuntimeException.class);
  15. assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
  16. assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1);
  17. assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(0);
  18. // Then the helloWorldService should be invoked 1 time
  19. BDDMockito.then(helloWorldService).should(Mockito.times(1)).returnHelloWorld();
  20. }

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

  1. @Test
  2. public void shouldConsumeOnFailureEvent() throws Throwable {
  3. rateLimiter.getEventPublisher()
  4. .onFailure(event ->
  5. logger.info(event.getEventType().toString()));
  6. rateLimiter.executeSupplier(() -> "Hello world");
  7. Try.ofSupplier(RateLimiter.decorateSupplier(rateLimiter, () -> "Hello world"));
  8. then(logger).should(times(1)).info("FAILED_ACQUIRE");
  9. }

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

  1. @Test
  2. public void shouldConsumeOnCallFinishedEventWhenExecutionIsFinished() throws Exception {
  3. // Given
  4. Bulkhead bulkhead = Bulkhead.of("test", config);
  5. // When
  6. bulkhead.getEventPublisher()
  7. .onCallFinished(event ->
  8. logger.info(event.getEventType().toString()));
  9. Try.ofSupplier(Bulkhead.decorateSupplier(bulkhead,helloWorldService::returnHelloWorld));
  10. // Then
  11. then(logger).should(times(1)).info("CALL_FINISHED");
  12. }

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

  1. @Test
  2. public void shouldConsumeOnCallRejectedEvent() {
  3. // Given
  4. Bulkhead bulkhead = Bulkhead.of("test", config);
  5. // When
  6. bulkhead.getEventPublisher()
  7. .onCallRejected(event ->
  8. logger.info(event.getEventType().toString()));
  9. bulkhead.isCallPermitted();
  10. Try.ofSupplier(Bulkhead.decorateSupplier(bulkhead,helloWorldService::returnHelloWorld));
  11. // Then
  12. then(logger).should(times(1)).info("CALL_REJECTED");
  13. }

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

  1. @Test
  2. public void shouldRegisterMetricsWithRetry() throws Throwable {
  3. //Given
  4. RetryRegistry retryRegistry = RetryRegistry.ofDefaults();
  5. Retry retry = retryRegistry.retry("testName");
  6. metricRegistry.registerAll(RetryMetrics.ofRetryRegistry(retryRegistry));
  7. // Given the HelloWorldService returns Hello world
  8. BDDMockito.given(helloWorldService.returnHelloWorld())
  9. .willThrow(new WebServiceException("BAM!"))
  10. .willReturn("Hello world")
  11. .willThrow(new WebServiceException("BAM!"))
  12. .willThrow(new WebServiceException("BAM!"))
  13. .willThrow(new WebServiceException("BAM!"));
  14. // Setup circuitbreaker with retry
  15. String value1 = retry.executeSupplier(helloWorldService::returnHelloWorld);
  16. Try.ofSupplier(Retry.decorateSupplier(retry, helloWorldService::returnHelloWorld));
  17. //Then
  18. assertThat(value1).isEqualTo("Hello world");
  19. // Then the helloWorldService should be invoked 1 time
  20. BDDMockito.then(helloWorldService).should(times(5)).returnHelloWorld();
  21. assertThat(metricRegistry.getMetrics()).hasSize(4);
  22. assertThat(metricRegistry.getGauges().get("resilience4j.retry.testName." + SUCCESSFUL_CALLS_WITH_RETRY).getValue()).isEqualTo(1L);
  23. assertThat(metricRegistry.getGauges().get("resilience4j.retry.testName." + SUCCESSFUL_CALLS_WITHOUT_RETRY).getValue()).isEqualTo(0L);
  24. assertThat(metricRegistry.getGauges().get("resilience4j.retry.testName." + FAILED_CALLS_WITH_RETRY).getValue()).isEqualTo(1L);
  25. assertThat(metricRegistry.getGauges().get("resilience4j.retry.testName." + FAILED_CALLS_WITHOUT_RETRY).getValue()).isEqualTo(0L);
  26. }

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

  1. @Test
  2. public void shouldConsumeOnRetryEvent() {
  3. given(helloWorldService.returnHelloWorld())
  4. .willThrow(new WebServiceException("BAM!"));
  5. retry.getEventPublisher()
  6. .onRetry(event ->
  7. logger.info(event.getEventType().toString()));
  8. Try.ofSupplier(Retry.decorateSupplier(retry, helloWorldService::returnHelloWorld));
  9. then(helloWorldService).should(times(3)).returnHelloWorld();
  10. then(logger).should(times(2)).info("RETRY");
  11. }

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

  1. @Test
  2. public void shouldConsumeOnErrorEvent() {
  3. given(helloWorldService.returnHelloWorld())
  4. .willThrow(new WebServiceException("BAM!"));
  5. retry.getEventPublisher()
  6. .onError(event ->
  7. logger.info(event.getEventType().toString()));
  8. Try.ofSupplier(Retry.decorateSupplier(retry, helloWorldService::returnHelloWorld));
  9. then(logger).should(times(1)).info("ERROR");
  10. then(helloWorldService).should(times(3)).returnHelloWorld();
  11. }

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

  1. @Test
  2. public void shouldConsumeIgnoredErrorEvent() {
  3. given(helloWorldService.returnHelloWorld())
  4. .willThrow(new WebServiceException("BAM!"));
  5. RetryConfig retryConfig = RetryConfig.custom()
  6. .retryOnException(throwable -> Match(throwable).of(
  7. Case($(instanceOf(WebServiceException.class)), false),
  8. Case($(), true)))
  9. .build();
  10. retry = Retry.of("testName", retryConfig);
  11. retry.getEventPublisher()
  12. .onIgnoredError(event ->
  13. logger.info(event.getEventType().toString()));
  14. Try.ofSupplier(Retry.decorateSupplier(retry, helloWorldService::returnHelloWorld));
  15. then(logger).should(times(1)).info("IGNORED_ERROR");
  16. then(helloWorldService).should(times(1)).returnHelloWorld();
  17. }

代码示例来源:origin: com.github.robozonky/robozonky-common

  1. private static <O> Either<Throwable, O> execute(final Supplier<O> operation) {
  2. LOGGER.trace("Will execute {}.", operation);
  3. return Try.ofSupplier(operation).map(Either::<Throwable, O>right)
  4. .recover(t -> {
  5. LOGGER.debug("Operation failed.", t);
  6. return Either.left(t);
  7. }).get();
  8. }

代码示例来源:origin: RoboZonky/robozonky

  1. private static <O> Either<Throwable, O> execute(final Supplier<O> operation) {
  2. LOGGER.trace("Will execute {}.", operation);
  3. return Try.ofSupplier(operation).map(Either::<Throwable, O>right)
  4. .recover(t -> {
  5. LOGGER.debug("Operation failed.", t);
  6. return Either.left(t);
  7. }).get();
  8. }

代码示例来源:origin: RoboZonky/robozonky

  1. CompletableFuture<Void> refreshIfNotAlreadyRefreshing(final CompletableFuture<Void> old) {
  2. if (old == null || old.isDone()) {
  3. logger.trace("Starting async reload.");
  4. final Runnable asyncOperation = () -> Try.ofSupplier(() -> getOperation().apply(value.get()))
  5. .peek(v -> processRetrievedValue(v, value::set)) // set the value on success
  6. .getOrElseGet(t -> {
  7. logger.warn("Async reload failed, operating with stale value.", t);
  8. return null;
  9. });
  10. return CompletableFuture.runAsync(asyncOperation, Scheduler.inBackground().getExecutor());
  11. } else {
  12. logger.trace("Reload already in progress on {} with {}.", this, old);
  13. return old;
  14. }
  15. }

代码示例来源:origin: com.github.robozonky/robozonky-common

  1. CompletableFuture<Void> refresh(final CompletableFuture<Void> old) {
  2. if (old == null || old.isDone()) {
  3. logger.trace("Starting async reload.");
  4. final Runnable asyncOperation = () -> Try.ofSupplier(getOperation())
  5. .peek(v -> processRetrievedValue(v, value::set)) // set the value on success
  6. .getOrElseGet(t -> {
  7. logger.warn("Async reload failed, operating with stale value.", t);
  8. return null;
  9. });
  10. return CompletableFuture.runAsync(asyncOperation, Scheduler.inBackground().getExecutor());
  11. } else {
  12. logger.trace("Reload already in progress on {} with {}.", this, old);
  13. return old;
  14. }
  15. }

代码示例来源:origin: com.github.robozonky/robozonky-common

  1. @Override
  2. public synchronized Either<Throwable, T> get() {
  3. if (!needsReload()) {
  4. logger.trace("Not reloading {}.", this);
  5. return Either.right(value.get());
  6. }
  7. logger.trace("Reloading {}.", this);
  8. return Try.ofSupplier(getOperation())
  9. .peek(v -> processRetrievedValue(v, value::set))
  10. .toEither();
  11. }
  12. }

代码示例来源:origin: RoboZonky/robozonky

  1. @Override
  2. public Either<Throwable, T> get() {
  3. if (needsReload()) { // double-checked locking to make sure the reload only happens once
  4. synchronized (this) {
  5. if (needsReload()) {
  6. logger.trace("Reloading {}.", this);
  7. return Try.ofSupplier(() -> getOperation().apply(value.get()))
  8. .peek(v -> processRetrievedValue(v, value::set))
  9. .toEither();
  10. }
  11. // otherwise fall through to retrieve the value
  12. }
  13. }
  14. logger.trace("Not reloading {}.", this);
  15. return Either.right(value.get());
  16. }

代码示例来源:origin: com.github.robozonky/robozonky-common

  1. @Override
  2. public synchronized Either<Throwable, T> get() {
  3. if (value.get() == null) { // force value retrieval and wait for it
  4. logger.debug("Fetching initial value synchronously on {}.", this);
  5. return Try.ofSupplier(getOperation())
  6. .peek(v -> processRetrievedValue(v, value::set))
  7. .toEither();
  8. }
  9. if (!needsReload()) { // return old value
  10. logger.trace("Not reloading {}.", this);
  11. return Either.right(value.get());
  12. }
  13. // trigger retrieval but return existing value
  14. final CompletableFuture<Void> currentFuture = future.getAndUpdate(this::refresh);
  15. logger.debug("Retrieved potentially stale value on {}, while {}.", this, currentFuture);
  16. return Either.right(value.get());
  17. }
  18. }

代码示例来源:origin: RoboZonky/robozonky

  1. @Override
  2. public Either<Throwable, T> get() {
  3. if (!hasValue()) { // force value retrieval and wait for it
  4. synchronized (this) {
  5. if (!hasValue()) { // double-checked locking to make sure the value is only ever loaded once
  6. logger.debug("Fetching initial value synchronously on {}.", this);
  7. return Try.ofSupplier(() -> getOperation().apply(null))
  8. .peek(v -> processRetrievedValue(v, value::set))
  9. .toEither();
  10. }
  11. // otherwise fall through to retrieve the current value
  12. }
  13. }
  14. if (needsReload()) { // trigger value retrieval on the background
  15. synchronized (this) {
  16. final CompletableFuture<Void> currentFuture = future.getAndUpdate(this::refreshIfNotAlreadyRefreshing);
  17. logger.debug("Retrieved potentially stale value on {}, while {}.", this, currentFuture);
  18. }
  19. }
  20. // return the current value
  21. return Either.right(value.get());
  22. }

相关文章