当前位置: 首页>>代码示例>>Java>>正文


Java Failsafe类代码示例

本文整理汇总了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));
}
 
开发者ID:Nexmo,项目名称:comms-router,代码行数:24,代码来源:TaskDispatcher.java

示例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();
            });
}
 
开发者ID:kawasima,项目名称:bouncr,代码行数:22,代码来源:WebHook.java

示例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);
}
 
开发者ID:brianm,项目名称:muckery,代码行数:26,代码来源:FailsafeTest.java

示例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));
}
 
开发者ID:tjheslin1,项目名称:Patterdale,代码行数:25,代码来源:HikariDataSourceProvider.java

示例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);
    }
}
 
开发者ID:StubbornJava,项目名称:StubbornJava,代码行数:8,代码来源:Retry.java

示例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);
}
 
开发者ID:kawasima,项目名称:bouncr,代码行数:39,代码来源:SignInController.java

示例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;
    };
}
 
开发者ID:zalando,项目名称:riptide,代码行数:16,代码来源:FailsafePlugin.java

示例8: call

import net.jodah.failsafe.Failsafe; //导入依赖的package包/类
@Override
protected <T> T call(Supplier<T> callable) {
  return Failsafe.with(circuitBreaker).get(callable::get);
}
 
开发者ID:HubSpot,项目名称:S3Decorators,代码行数:5,代码来源:FailsafeS3Decorator.java

示例9: sayHelloWorldReliable

import net.jodah.failsafe.Failsafe; //导入依赖的package包/类
@RequestMapping("/reliable")
public String sayHelloWorldReliable() {
    return Failsafe.with(breaker).withFallback("Service unavailable").get(this::getMessage);
}
 
开发者ID:zalando,项目名称:failsafe-actuator,代码行数:5,代码来源:SampleController.java

示例10: sayHelloWorldReliableWithDelay

import net.jodah.failsafe.Failsafe; //导入依赖的package包/类
@RequestMapping("/reliableWithDelay")
public String sayHelloWorldReliableWithDelay() {
    return Failsafe.with(delayBreaker).withFallback("Service unavailable").get(this::getMessage);
}
 
开发者ID:zalando,项目名称:failsafe-actuator,代码行数:5,代码来源:SampleController.java

示例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());
}
 
开发者ID:zalando-stups,项目名称:baigan-config,代码行数:5,代码来源:S3FileLoader.java


注:本文中的net.jodah.failsafe.Failsafe类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。