本文整理了Java中io.vavr.control.Try.ofSupplier()
方法的一些代码示例,展示了Try.ofSupplier()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Try.ofSupplier()
方法的具体详情如下:
包路径:io.vavr.control.Try
类名称:Try
方法名:ofSupplier
[英]Creates a Try of a Supplier.
[中]创建一个供应商的尝试。
代码示例来源:origin: resilience4j/resilience4j
@Test
public void shouldDecorateSupplierAndReturnWithException() {
// Given
CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName");
CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0);
// Given the HelloWorldService throws an exception
BDDMockito.given(helloWorldService.returnHelloWorld()).willThrow(new RuntimeException("BAM!"));
//When
Supplier<String> supplier = CircuitBreaker.decorateSupplier(circuitBreaker, helloWorldService::returnHelloWorld);
//Then
Try<String> result = Try.ofSupplier(supplier);
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);
// Then the helloWorldService should be invoked 1 time
BDDMockito.then(helloWorldService).should(Mockito.times(1)).returnHelloWorld();
}
代码示例来源:origin: resilience4j/resilience4j
@Test
public void shouldConsumeOnFailureEvent() throws Throwable {
rateLimiter.getEventPublisher()
.onFailure(event ->
logger.info(event.getEventType().toString()));
rateLimiter.executeSupplier(() -> "Hello world");
Try.ofSupplier(RateLimiter.decorateSupplier(rateLimiter, () -> "Hello world"));
then(logger).should(times(1)).info("FAILED_ACQUIRE");
}
代码示例来源:origin: resilience4j/resilience4j
@Test
public void shouldConsumeOnCallFinishedEventWhenExecutionIsFinished() throws Exception {
// Given
Bulkhead bulkhead = Bulkhead.of("test", config);
// When
bulkhead.getEventPublisher()
.onCallFinished(event ->
logger.info(event.getEventType().toString()));
Try.ofSupplier(Bulkhead.decorateSupplier(bulkhead,helloWorldService::returnHelloWorld));
// Then
then(logger).should(times(1)).info("CALL_FINISHED");
}
代码示例来源:origin: resilience4j/resilience4j
@Test
public void shouldConsumeOnCallRejectedEvent() {
// Given
Bulkhead bulkhead = Bulkhead.of("test", config);
// When
bulkhead.getEventPublisher()
.onCallRejected(event ->
logger.info(event.getEventType().toString()));
bulkhead.isCallPermitted();
Try.ofSupplier(Bulkhead.decorateSupplier(bulkhead,helloWorldService::returnHelloWorld));
// Then
then(logger).should(times(1)).info("CALL_REJECTED");
}
代码示例来源:origin: resilience4j/resilience4j
@Test
public void shouldRegisterMetricsWithRetry() throws Throwable {
//Given
RetryRegistry retryRegistry = RetryRegistry.ofDefaults();
Retry retry = retryRegistry.retry("testName");
metricRegistry.registerAll(RetryMetrics.ofRetryRegistry(retryRegistry));
// Given the HelloWorldService returns Hello world
BDDMockito.given(helloWorldService.returnHelloWorld())
.willThrow(new WebServiceException("BAM!"))
.willReturn("Hello world")
.willThrow(new WebServiceException("BAM!"))
.willThrow(new WebServiceException("BAM!"))
.willThrow(new WebServiceException("BAM!"));
// Setup circuitbreaker with retry
String value1 = retry.executeSupplier(helloWorldService::returnHelloWorld);
Try.ofSupplier(Retry.decorateSupplier(retry, helloWorldService::returnHelloWorld));
//Then
assertThat(value1).isEqualTo("Hello world");
// Then the helloWorldService should be invoked 1 time
BDDMockito.then(helloWorldService).should(times(5)).returnHelloWorld();
assertThat(metricRegistry.getMetrics()).hasSize(4);
assertThat(metricRegistry.getGauges().get("resilience4j.retry.testName." + SUCCESSFUL_CALLS_WITH_RETRY).getValue()).isEqualTo(1L);
assertThat(metricRegistry.getGauges().get("resilience4j.retry.testName." + SUCCESSFUL_CALLS_WITHOUT_RETRY).getValue()).isEqualTo(0L);
assertThat(metricRegistry.getGauges().get("resilience4j.retry.testName." + FAILED_CALLS_WITH_RETRY).getValue()).isEqualTo(1L);
assertThat(metricRegistry.getGauges().get("resilience4j.retry.testName." + FAILED_CALLS_WITHOUT_RETRY).getValue()).isEqualTo(0L);
}
代码示例来源:origin: resilience4j/resilience4j
@Test
public void shouldConsumeOnRetryEvent() {
given(helloWorldService.returnHelloWorld())
.willThrow(new WebServiceException("BAM!"));
retry.getEventPublisher()
.onRetry(event ->
logger.info(event.getEventType().toString()));
Try.ofSupplier(Retry.decorateSupplier(retry, helloWorldService::returnHelloWorld));
then(helloWorldService).should(times(3)).returnHelloWorld();
then(logger).should(times(2)).info("RETRY");
}
代码示例来源:origin: resilience4j/resilience4j
@Test
public void shouldConsumeOnErrorEvent() {
given(helloWorldService.returnHelloWorld())
.willThrow(new WebServiceException("BAM!"));
retry.getEventPublisher()
.onError(event ->
logger.info(event.getEventType().toString()));
Try.ofSupplier(Retry.decorateSupplier(retry, helloWorldService::returnHelloWorld));
then(logger).should(times(1)).info("ERROR");
then(helloWorldService).should(times(3)).returnHelloWorld();
}
代码示例来源:origin: resilience4j/resilience4j
@Test
public void shouldConsumeIgnoredErrorEvent() {
given(helloWorldService.returnHelloWorld())
.willThrow(new WebServiceException("BAM!"));
RetryConfig retryConfig = RetryConfig.custom()
.retryOnException(throwable -> Match(throwable).of(
Case($(instanceOf(WebServiceException.class)), false),
Case($(), true)))
.build();
retry = Retry.of("testName", retryConfig);
retry.getEventPublisher()
.onIgnoredError(event ->
logger.info(event.getEventType().toString()));
Try.ofSupplier(Retry.decorateSupplier(retry, helloWorldService::returnHelloWorld));
then(logger).should(times(1)).info("IGNORED_ERROR");
then(helloWorldService).should(times(1)).returnHelloWorld();
}
代码示例来源:origin: com.github.robozonky/robozonky-common
private static <O> Either<Throwable, O> execute(final Supplier<O> operation) {
LOGGER.trace("Will execute {}.", operation);
return Try.ofSupplier(operation).map(Either::<Throwable, O>right)
.recover(t -> {
LOGGER.debug("Operation failed.", t);
return Either.left(t);
}).get();
}
代码示例来源:origin: RoboZonky/robozonky
private static <O> Either<Throwable, O> execute(final Supplier<O> operation) {
LOGGER.trace("Will execute {}.", operation);
return Try.ofSupplier(operation).map(Either::<Throwable, O>right)
.recover(t -> {
LOGGER.debug("Operation failed.", t);
return Either.left(t);
}).get();
}
代码示例来源:origin: RoboZonky/robozonky
CompletableFuture<Void> refreshIfNotAlreadyRefreshing(final CompletableFuture<Void> old) {
if (old == null || old.isDone()) {
logger.trace("Starting async reload.");
final Runnable asyncOperation = () -> Try.ofSupplier(() -> getOperation().apply(value.get()))
.peek(v -> processRetrievedValue(v, value::set)) // set the value on success
.getOrElseGet(t -> {
logger.warn("Async reload failed, operating with stale value.", t);
return null;
});
return CompletableFuture.runAsync(asyncOperation, Scheduler.inBackground().getExecutor());
} else {
logger.trace("Reload already in progress on {} with {}.", this, old);
return old;
}
}
代码示例来源:origin: com.github.robozonky/robozonky-common
CompletableFuture<Void> refresh(final CompletableFuture<Void> old) {
if (old == null || old.isDone()) {
logger.trace("Starting async reload.");
final Runnable asyncOperation = () -> Try.ofSupplier(getOperation())
.peek(v -> processRetrievedValue(v, value::set)) // set the value on success
.getOrElseGet(t -> {
logger.warn("Async reload failed, operating with stale value.", t);
return null;
});
return CompletableFuture.runAsync(asyncOperation, Scheduler.inBackground().getExecutor());
} else {
logger.trace("Reload already in progress on {} with {}.", this, old);
return old;
}
}
代码示例来源:origin: com.github.robozonky/robozonky-common
@Override
public synchronized Either<Throwable, T> get() {
if (!needsReload()) {
logger.trace("Not reloading {}.", this);
return Either.right(value.get());
}
logger.trace("Reloading {}.", this);
return Try.ofSupplier(getOperation())
.peek(v -> processRetrievedValue(v, value::set))
.toEither();
}
}
代码示例来源:origin: RoboZonky/robozonky
@Override
public Either<Throwable, T> get() {
if (needsReload()) { // double-checked locking to make sure the reload only happens once
synchronized (this) {
if (needsReload()) {
logger.trace("Reloading {}.", this);
return Try.ofSupplier(() -> getOperation().apply(value.get()))
.peek(v -> processRetrievedValue(v, value::set))
.toEither();
}
// otherwise fall through to retrieve the value
}
}
logger.trace("Not reloading {}.", this);
return Either.right(value.get());
}
代码示例来源:origin: com.github.robozonky/robozonky-common
@Override
public synchronized Either<Throwable, T> get() {
if (value.get() == null) { // force value retrieval and wait for it
logger.debug("Fetching initial value synchronously on {}.", this);
return Try.ofSupplier(getOperation())
.peek(v -> processRetrievedValue(v, value::set))
.toEither();
}
if (!needsReload()) { // return old value
logger.trace("Not reloading {}.", this);
return Either.right(value.get());
}
// trigger retrieval but return existing value
final CompletableFuture<Void> currentFuture = future.getAndUpdate(this::refresh);
logger.debug("Retrieved potentially stale value on {}, while {}.", this, currentFuture);
return Either.right(value.get());
}
}
代码示例来源:origin: RoboZonky/robozonky
@Override
public Either<Throwable, T> get() {
if (!hasValue()) { // force value retrieval and wait for it
synchronized (this) {
if (!hasValue()) { // double-checked locking to make sure the value is only ever loaded once
logger.debug("Fetching initial value synchronously on {}.", this);
return Try.ofSupplier(() -> getOperation().apply(null))
.peek(v -> processRetrievedValue(v, value::set))
.toEither();
}
// otherwise fall through to retrieve the current value
}
}
if (needsReload()) { // trigger value retrieval on the background
synchronized (this) {
final CompletableFuture<Void> currentFuture = future.getAndUpdate(this::refreshIfNotAlreadyRefreshing);
logger.debug("Retrieved potentially stale value on {}, while {}.", this, currentFuture);
}
}
// return the current value
return Either.right(value.get());
}
内容来源于网络,如有侵权,请联系作者删除!