本文整理汇总了Java中net.jodah.failsafe.Failsafe类的典型用法代码示例。如果您正苦于以下问题:Java Failsafe类的具体用法?Java Failsafe怎么用?Java Failsafe使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Failsafe类属于net.jodah.failsafe包,在下文中一共展示了Failsafe类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: submitTaskAssignment
import net.jodah.failsafe.Failsafe; //导入依赖的package包/类
public void submitTaskAssignment(TaskAssignmentDto taskAssignmentDto) {
RetryPolicy retryPolicy = this.retryPolicy.copy();
retryPolicy.abortIf(obj -> {
try {
return db.transactionManager.execute(em -> {
Task task = db.task.get(em, taskAssignmentDto.getTask());
return task.getState() != TaskState.assigned;
});
} catch (CommsRouterException e) {
LOGGER.debug("Error retrieving Task: {}", taskAssignmentDto.getTask().getRef());
return true;
}
});
Failsafe.with(retryPolicy).with(threadPool)
.onSuccess((ignored, executionContext) -> LOGGER.debug("Task {} assigned to agent {}",
taskAssignmentDto.getTask(), taskAssignmentDto.getAgent()))
.onRetry(
(result, failure, context) -> LOGGER.warn("Retry assigning task {} to agent {}: {}, {}",
taskAssignmentDto.getTask(), taskAssignmentDto.getAgent(), failure, context))
.onFailure((ignored, throwable) -> LOGGER.error("Failure assigning task {} to agent {}: {}",
taskAssignmentDto.getTask(), taskAssignmentDto.getAgent(), throwable, throwable))
.run(() -> taskEventHandler.onTaskAssigned(taskAssignmentDto));
}
示例2: run
import net.jodah.failsafe.Failsafe; //导入依赖的package包/类
@Override
public void run(T object) {
RetryPolicy retryPolicy = method.equalsIgnoreCase("get") ? idempotent : notIdempotent;
Failsafe.with(retryPolicy)
.with(executor)
.onSuccess(response -> {
})
.get(() -> {
RequestBody body = RequestBody.create(JSON, mapper.writeValueAsString(object));
Request.Builder requestBuilder;
requestBuilder = new Request.Builder()
.url(url)
.header("content-type", "application/json")
.method(method, body);
if (headers != null) {
headers.forEach(requestBuilder::addHeader);
}
return client.newCall(requestBuilder.build()).execute();
});
}
示例3: testFoo
import net.jodah.failsafe.Failsafe; //导入依赖的package包/类
@Test
public void testFoo() throws Exception {
CircuitBreaker cb = new CircuitBreaker().failOn(RuntimeException.class)
.withDelay(1, TimeUnit.SECONDS)
.withFailureThreshold(1, 1);
AsyncFailsafe<?> fs = Failsafe.with(cb)
.with(clock)
.withFallback(Failsafer.bounce());
CompletableFuture<String> f = fs.future(() -> service.execute(() -> "hello"));
f.get();
assertThat(f).isCompletedWithValue("hello");
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.CLOSED);
f = fs.future(() -> service.execute(() -> {
throw new RuntimeException("NooOoOooO");
}));
assertThatThrownBy(f::get).hasCauseInstanceOf(RuntimeException.class)
.hasMessageContaining("NooOoOooO");
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.OPEN);
f = fs.future(() -> service.execute(() -> "yes"));
assertThatThrownBy(f::get).hasCauseInstanceOf(CircuitBreakerOpenException.class);
}
示例4: retriableDataSource
import net.jodah.failsafe.Failsafe; //导入依赖的package包/类
/**
* Attempts to create a {@link HikariDataSource} by making an initial connection to the database.
* Retries a number of times, with a delay between each retry, according to the provided {@link PatterdaleRuntimeParameters}.
*
* Failed attempts are logged as well as when the number of retries has exceeded.
*
* @param runtimeParams The app configuration defined in `patterdale.yml`.
* @param databaseDefinition The details of the database being connected to.
* @param passwords The separate store of passwords, the matching password will be found according to the `databaseDefinition`.
* @param logger to log.
* @return A data source for a successful connection to the database.
*/
public static HikariDataSource retriableDataSource(PatterdaleRuntimeParameters runtimeParams, DatabaseDefinition databaseDefinition, Passwords passwords, Logger logger) {
RetryPolicy retryPolicy = new RetryPolicy()
.retryOn(HikariPool.PoolInitializationException.class)
.withDelay(runtimeParams.connectionRetryDelayInSeconds(), TimeUnit.SECONDS)
.withMaxRetries(runtimeParams.maxConnectionRetries());
return Failsafe.with(retryPolicy)
.onRetry((result, failure, context) -> logRetry(runtimeParams, databaseDefinition, logger))
.onFailedAttempt((result, failure, context) -> logFailedAttempt(databaseDefinition, logger))
.onRetriesExceeded(throwable -> logRetriesExceeded(databaseDefinition, logger))
.get(() -> dataSource(runtimeParams, databaseDefinition, passwords, logger));
}
示例5: retryUntilSuccessfulWithBackoff
import net.jodah.failsafe.Failsafe; //导入依赖的package包/类
public static String retryUntilSuccessfulWithBackoff(Callable<Response> callable) {
try (Response response = Failsafe.with(HTTP_200_RETRY).get(callable)) {
return response.body().string();
} catch (IOException e) {
throw Exceptions.sneaky(e);
}
}
示例6: signInByOidc
import net.jodah.failsafe.Failsafe; //导入依赖的package包/类
public HttpResponse signInByOidc(HttpRequest request, Parameters params) {
OidcProviderDao oidcProviderDao = daoProvider.getDao(OidcProviderDao.class);
OidcProvider oidcProvider = oidcProviderDao.selectById(params.getLong("id"));
if (oidcProvider.getResponseType() == ID_TOKEN || oidcProvider.getResponseType() == ResponseType.TOKEN) {
return templateEngine.render("my/signIn/oidc_implicit",
"oidcProvider", oidcProvider);
}
String oidcSessionId = some(request.getCookies().get("OIDC_SESSION_ID"), Cookie::getValue).orElse(null);
OidcSession oidcSession = (OidcSession) storeProvider.getStore(OIDC_SESSION).read(oidcSessionId);
if (!Objects.equals(oidcSession.getState(), params.get("state"))) {
return signInForm(request, (SignInForm) builder(new SignInForm())
.set(SignInForm::setErrors, Multimap.of("account", "error.failToSignin"))
.build());
}
OidcProviderDto oidcProviderDto = beansConverter.createFrom(oidcProvider, OidcProviderDto.class);
oidcProviderDto.setRedirectUriBase(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort());
HashMap<String, Object> res = Failsafe.with(config.getHttpClientRetryPolicy()).get(() -> {
Response response = OKHTTP.newCall(new Request.Builder()
.url(oidcProvider.getTokenEndpoint())
.header("Authorization", "Basic " +
Base64.getUrlEncoder().encodeToString((oidcProvider.getApiKey() + ":" + oidcProvider.getApiSecret()).getBytes()))
.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),
"grant_type=authorization_code&code=" + params.get("code") +
"&redirect_uri=" + oidcProviderDto.getRedirectUri()))
.build())
.execute();
if (response.code() == 503) throw new FalteringEnvironmentException();
try(InputStream in = response.body().byteStream()) {
ObjectMapper jsonMapper = new ObjectMapper();
HashMap<String, Object> map = jsonMapper.readValue(in, GENERAL_JSON_REF);
return map;
}
});
String encodedIdToken = (String) res.get("id_token");
return connectOpenIdToBoucrUser(encodedIdToken, oidcProvider, request);
}
示例7: prepare
import net.jodah.failsafe.Failsafe; //导入依赖的package包/类
@Override
public RequestExecution prepare(final RequestArguments arguments, final RequestExecution execution) {
return () -> {
final CompletableFuture<ClientHttpResponse> original = Failsafe
.with(retryPolicy)
.with(circuitBreaker)
.with(scheduler)
// TODO allow to register listeners
.future(execution::execute);
final CompletableFuture<ClientHttpResponse> cancelable = preserveCancelability(original);
original.whenComplete(forwardTo(cancelable));
return cancelable;
};
}
示例8: call
import net.jodah.failsafe.Failsafe; //导入依赖的package包/类
@Override
protected <T> T call(Supplier<T> callable) {
return Failsafe.with(circuitBreaker).get(callable::get);
}
示例9: sayHelloWorldReliable
import net.jodah.failsafe.Failsafe; //导入依赖的package包/类
@RequestMapping("/reliable")
public String sayHelloWorldReliable() {
return Failsafe.with(breaker).withFallback("Service unavailable").get(this::getMessage);
}
示例10: sayHelloWorldReliableWithDelay
import net.jodah.failsafe.Failsafe; //导入依赖的package包/类
@RequestMapping("/reliableWithDelay")
public String sayHelloWorldReliableWithDelay() {
return Failsafe.with(delayBreaker).withFallback("Service unavailable").get(this::getMessage);
}
示例11: decryptValue
import net.jodah.failsafe.Failsafe; //导入依赖的package包/类
private ByteBuffer decryptValue(final byte[] encryptedBytes) {
final DecryptRequest request = new DecryptRequest().withCiphertextBlob(ByteBuffer.wrap(encryptedBytes));
return Failsafe.with(retryPolicy).get(() -> kmsClient.decrypt(request).getPlaintext());
}