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


Java WaitStrategies类代码示例

本文整理汇总了Java中com.github.rholder.retry.WaitStrategies的典型用法代码示例。如果您正苦于以下问题:Java WaitStrategies类的具体用法?Java WaitStrategies怎么用?Java WaitStrategies使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


WaitStrategies类属于com.github.rholder.retry包,在下文中一共展示了WaitStrategies类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: restore

import com.github.rholder.retry.WaitStrategies; //导入依赖的package包/类
@Override
public void restore() {
  // Failing here means restarting the styx scheduler and replaying all events again. This is quite time consuming
  // and distressing when deploying, so try hard.
  final Retryer<Object> retryer = RetryerBuilder.newBuilder()
      .retryIfException()
      .withWaitStrategy(WaitStrategies.exponentialWait(10, TimeUnit.SECONDS))
      .withStopStrategy(StopStrategies.stopAfterAttempt(10))
      .withRetryListener(this::onRestorePollPodsAttempt)
      .build();

  try {
    retryer.call(Executors.callable(this::tryPollPods));
  } catch (ExecutionException | RetryException e) {
    throw new RuntimeException(e);
  }
}
 
开发者ID:spotify,项目名称:styx,代码行数:18,代码来源:KubernetesDockerRunner.java

示例2: executeFunctionWithRetrying

import com.github.rholder.retry.WaitStrategies; //导入依赖的package包/类
private String executeFunctionWithRetrying(Callable<String> callable) throws RetryException, ExecutionException {
    try {
        Retryer<String> retryer = RetryerBuilder.<String>newBuilder()
                .retryIfExceptionOfType(TemporaryWriteException.class)
                .withRetryListener(retryLogger)
                .withWaitStrategy(WaitStrategies.exponentialWait(100, 5, TimeUnit.MINUTES))
                .withStopStrategy(StopStrategies.stopAfterAttempt(MAX_RETRY))
                .build();

        return retryer.call(callable);
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        } else {
            throw e;
        }
    }
}
 
开发者ID:graknlabs,项目名称:grakn,代码行数:20,代码来源:GraqlController.java

示例3: RetryHelper

import com.github.rholder.retry.WaitStrategies; //导入依赖的package包/类
@Inject
RetryHelper(
    @GerritServerConfig Config cfg,
    Metrics metrics,
    NotesMigration migration,
    ReviewDbBatchUpdate.AssistedFactory reviewDbBatchUpdateFactory,
    NoteDbBatchUpdate.AssistedFactory noteDbBatchUpdateFactory) {
  this.metrics = metrics;
  this.migration = migration;
  this.updateFactory =
      new BatchUpdate.Factory(migration, reviewDbBatchUpdateFactory, noteDbBatchUpdateFactory);
  this.defaultTimeout =
      Duration.ofMillis(
          cfg.getTimeUnit("noteDb", null, "retryTimeout", SECONDS.toMillis(20), MILLISECONDS));
  this.waitStrategy =
      WaitStrategies.join(
          WaitStrategies.exponentialWait(
              cfg.getTimeUnit("noteDb", null, "retryMaxWait", SECONDS.toMillis(5), MILLISECONDS),
              MILLISECONDS),
          WaitStrategies.randomWait(50, MILLISECONDS));
}
 
开发者ID:gerrit-review,项目名称:gerrit,代码行数:22,代码来源:RetryHelper.java

示例4: ensureRebuiltRetryer

import com.github.rholder.retry.WaitStrategies; //导入依赖的package包/类
private Retryer<NoteDbChangeState> ensureRebuiltRetryer(Stopwatch sw) {
  if (testEnsureRebuiltRetryer != null) {
    return testEnsureRebuiltRetryer;
  }
  // Retry the ensureRebuilt step with backoff until half the timeout has
  // expired, leaving the remaining half for the rest of the steps.
  long remainingNanos = (MILLISECONDS.toNanos(timeoutMs) / 2) - sw.elapsed(NANOSECONDS);
  remainingNanos = Math.max(remainingNanos, 0);
  return RetryerBuilder.<NoteDbChangeState>newBuilder()
      .retryIfException(e -> (e instanceof IOException) || (e instanceof OrmException))
      .withWaitStrategy(
          WaitStrategies.join(
              WaitStrategies.exponentialWait(250, MILLISECONDS),
              WaitStrategies.randomWait(50, MILLISECONDS)))
      .withStopStrategy(StopStrategies.stopAfterDelay(remainingNanos, NANOSECONDS))
      .build();
}
 
开发者ID:gerrit-review,项目名称:gerrit,代码行数:18,代码来源:PrimaryStorageMigrator.java

示例5: createRemoteConnection

import com.github.rholder.retry.WaitStrategies; //导入依赖的package包/类
@Override
public RemoteConnection createRemoteConnection(String remoteAddress, RemoteType remoteType,
    LoginCredential loginCredential, int port) {

  Callable<RemoteConnection> callable = () -> remoteConnectionFactory
      .createRemoteConnection(remoteAddress, remoteType, loginCredential, port);

  Retryer<RemoteConnection> remoteConnectionRetryer =
      RetryerBuilder.<RemoteConnection>newBuilder().retryIfRuntimeException()
          .retryIfException(throwable -> throwable instanceof RemoteException)
          .withStopStrategy(StopStrategies.stopAfterAttempt(connectionRetries))
          .withWaitStrategy(WaitStrategies
              .exponentialWait(exponentialMultiplier, exponentialMaxTime, TimeUnit.SECONDS))
          .build();

  try {
    return remoteConnectionRetryer.call(callable);
  } catch (ExecutionException | RetryException e) {
    throw new RuntimeException(e);
  }
}
 
开发者ID:cloudiator,项目名称:sword,代码行数:22,代码来源:RetryingConnectionFactory.java

示例6: BaseJdbcBufferedInserter

import com.github.rholder.retry.WaitStrategies; //导入依赖的package包/类
public BaseJdbcBufferedInserter(State state, Connection conn) {
  this.conn = conn;
  this.batchSize = state.getPropAsInt(WRITER_JDBC_INSERT_BATCH_SIZE, DEFAULT_WRITER_JDBC_INSERT_BATCH_SIZE);
  if (this.batchSize < 1) {
    throw new IllegalArgumentException(WRITER_JDBC_INSERT_BATCH_SIZE + " should be a positive number");
  }

  int maxWait = state.getPropAsInt(WRITER_JDBC_INSERT_RETRY_TIMEOUT, DEFAULT_WRITER_JDBC_INSERT_RETRY_TIMEOUT);
  int maxAttempts =
      state.getPropAsInt(WRITER_JDBC_INSERT_RETRY_MAX_ATTEMPT, DEFAULT_WRITER_JDBC_INSERT_RETRY_MAX_ATTEMPT);

  //retry after 2, 4, 8, 16... sec, allow at most maxWait sec delay
  this.retryer = RetryerBuilder.<Boolean> newBuilder().retryIfException()
      .withWaitStrategy(WaitStrategies.exponentialWait(1000, maxWait, TimeUnit.SECONDS))
      .withStopStrategy(StopStrategies.stopAfterAttempt(maxAttempts)).build();
}
 
开发者ID:apache,项目名称:incubator-gobblin,代码行数:17,代码来源:BaseJdbcBufferedInserter.java

示例7: createRetryBuilder

import com.github.rholder.retry.WaitStrategies; //导入依赖的package包/类
/**
 * @return RetryerBuilder that retries on all exceptions except NonTransientException with exponential back off
 */
public static RetryerBuilder<Void> createRetryBuilder(State state) {
  Predicate<Throwable> transients = new Predicate<Throwable>() {
    @Override
    public boolean apply(Throwable t) {
      return !(t instanceof NonTransientException);
    }
  };

  long multiplier = state.getPropAsLong(RETRY_MULTIPLIER, 500L);
  long maxWaitMsPerInterval = state.getPropAsLong(RETRY_MAX_WAIT_MS_PER_INTERVAL, 10000);
  int maxAttempts = state.getPropAsInt(RETRY_MAX_ATTEMPTS, 5);
  return RetryerBuilder.<Void> newBuilder()
      .retryIfException(transients)
      .withWaitStrategy(WaitStrategies.exponentialWait(multiplier, maxWaitMsPerInterval, TimeUnit.MILLISECONDS)) //1, 2, 4, 8, 16 seconds delay
      .withStopStrategy(StopStrategies.stopAfterAttempt(maxAttempts)); //Total 5 attempts and fail.
}
 
开发者ID:apache,项目名称:incubator-gobblin,代码行数:20,代码来源:RetryWriter.java

示例8: mock

import com.github.rholder.retry.WaitStrategies; //导入依赖的package包/类
public static void mock() {
    Waits.setInstance(new Wait() {
        @Override
        public void time(Duration waitTime) {
            // don't wait
        }

        @Override
        @SuppressWarnings("unchecked")
        protected <T> Retryer<T> getRetryer(Predicate<? super T> predicate, Duration timeout, Duration interval) {
            int numRetries = (int) (timeout.getTime() / interval.getTime());
            // we emulate the number of retries
            return RetryerBuilder.<T> newBuilder()
                    .retryIfResult(Predicates.not((Predicate<T>) predicate))
                    .retryIfRuntimeException()
                    .withWaitStrategy(WaitStrategies.noWait())
                    .withStopStrategy(StopStrategies.stopAfterAttempt(numRetries))
                    .build();
        }
    });
}
 
开发者ID:viltgroup,项目名称:minium,代码行数:22,代码来源:WaitMocks.java

示例9: SingularityClient

import com.github.rholder.retry.WaitStrategies; //导入依赖的package包/类
public SingularityClient(String contextPath, HttpClient httpClient, Provider<List<String>> hostsProvider, Optional<SingularityClientCredentials> credentials, boolean ssl, int retryAttempts, Predicate<HttpResponse> retryStrategy) {
  this.httpClient = httpClient;
  this.contextPath = contextPath;

  this.hostsProvider = hostsProvider;
  this.random = new Random();

  this.credentials = credentials;
  this.ssl = ssl;

  this.httpResponseRetryer = RetryerBuilder.<HttpResponse>newBuilder()
      .withStopStrategy(StopStrategies.stopAfterAttempt(retryAttempts))
      .withWaitStrategy(WaitStrategies.exponentialWait())
      .retryIfResult(retryStrategy::test)
      .retryIfException()
      .build();
}
 
开发者ID:HubSpot,项目名称:Singularity,代码行数:18,代码来源:SingularityClient.java

示例10: notifyService

import com.github.rholder.retry.WaitStrategies; //导入依赖的package包/类
public void notifyService(String action) throws Exception {
  long start = System.currentTimeMillis();
  Retryer<AgentCheckInResponse> retryer = RetryerBuilder.<AgentCheckInResponse>newBuilder()
      .retryIfException()
      .withStopStrategy(StopStrategies.stopAfterAttempt(configuration.getMaxNotifyServiceAttempts()))
      .withWaitStrategy(WaitStrategies.exponentialWait(1, TimeUnit.SECONDS))
      .build();

  AgentCheckInResponse agentCheckInResponse = retryer.call(checkInCallable(action, false));
  while ((agentCheckInResponse.getState() != TrafficSourceState.DONE
      && System.currentTimeMillis() - start < configuration.getAgentCheckInTimeoutMs())) {
    try {
      Thread.sleep(agentCheckInResponse.getWaitTime());
    } catch (InterruptedException ie) {
      LOG.error("Interrupted waiting for check in with service, shutting down early");
      break;
    }
    agentCheckInResponse = retryer.call(checkInCallable(action, true));
  }
  LOG.info("Finished agent check in");
}
 
开发者ID:HubSpot,项目名称:Baragon,代码行数:22,代码来源:LifecycleHelper.java

示例11: getGlobalStateWithRetry

import com.github.rholder.retry.WaitStrategies; //导入依赖的package包/类
private Collection<BaragonServiceState> getGlobalStateWithRetry() throws AgentServiceNotifyException {
  Callable<Collection<BaragonServiceState>> callable = new Callable<Collection<BaragonServiceState>>() {
    public Collection<BaragonServiceState> call() throws Exception {
      return getGlobalState();
    }
  };

  Retryer<Collection<BaragonServiceState>> retryer = RetryerBuilder.<Collection<BaragonServiceState>>newBuilder()
      .retryIfException()
      .withStopStrategy(StopStrategies.stopAfterAttempt(configuration.getMaxGetGloablStateAttempts()))
      .withWaitStrategy(WaitStrategies.exponentialWait(1, TimeUnit.SECONDS))
      .build();

  try {
    return retryer.call(callable);
  } catch (Exception e) {
    LOG.error("Could not get global state from Baragon Service");
    throw Throwables.propagate(e);
  }
}
 
开发者ID:HubSpot,项目名称:Baragon,代码行数:21,代码来源:LifecycleHelper.java

示例12: buildResponseRetryer

import com.github.rholder.retry.WaitStrategies; //导入依赖的package包/类
private Retryer<Response> buildResponseRetryer() {
	final RetryListener retryListener = new RetryListener() {
		@Override
		public <V> void onRetry(Attempt<V> attempt) {
			final long attemptNumber = attempt.getAttemptNumber();
			if (attemptNumber > ONE) {
				final long delaySinceFirstAttemptInMilliseconds = attempt.getDelaySinceFirstAttempt();
				final long delaySinceFirstAttemptInSeconds = TimeUnit.SECONDS
						.convert(delaySinceFirstAttemptInMilliseconds, TimeUnit.MILLISECONDS);
				final Response response = (Response) attempt.getResult();
				response.bufferEntity();
				LOGGER.warn(String.format(RETRY_ATTEMPT_MESSAGE, delaySinceFirstAttemptInSeconds, attemptNumber,
						response.getStatus(), response.readEntity(String.class)));
			}
		}
	};

	final long maximumWaitDuration = requestRetryConfiguration.getMininumWaitDuration() * TWO;
	return RetryerBuilder.<Response> newBuilder().retryIfResult(this::shouldRetryResponse)
			.withWaitStrategy(WaitStrategies.randomWait(requestRetryConfiguration.getMininumWaitDuration(),
					requestRetryConfiguration.getMininumWaitUnit(), maximumWaitDuration,
					requestRetryConfiguration.getMininumWaitUnit()))
			.withRetryListener(retryListener)
			.withStopStrategy(StopStrategies.stopAfterDelay(requestRetryConfiguration.getTimeoutDuration(),
					requestRetryConfiguration.getTimeoutUnit()))
			.build();
}
 
开发者ID:rjdavis3,项目名称:ebay-sdk,代码行数:28,代码来源:EbayClientImpl.java

示例13: uploadSingle

import com.github.rholder.retry.WaitStrategies; //导入依赖的package包/类
private void uploadSingle(int sequence, Path file) throws Exception {
  Callable<Boolean> uploader = new Uploader(sequence, file);

  Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
    .retryIfExceptionOfType(S3ServiceException.class)
    .retryIfRuntimeException()
    .withWaitStrategy(WaitStrategies.fixedWait(configuration.getRetryWaitMs(), TimeUnit.MILLISECONDS))
    .withStopStrategy(StopStrategies.stopAfterAttempt(configuration.getRetryCount()))
    .build();
  retryer.call(uploader);
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Mesos,代码行数:12,代码来源:SingularityS3Uploader.java

示例14: interrupt

import com.github.rholder.retry.WaitStrategies; //导入依赖的package包/类
@Override
public void interrupt() throws UnableToInterruptJobException {

    if (!isRunning()) throw new UnableToInterruptJobException("Job is not running!");

    synchronized (updateLock) {
        interruptRequested = true;

        executeThread.interrupt();
    }

    final Callable<Boolean> callable = new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return AbstractStatusInterruptableJob.this.isRunning();
        }
    };

    Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
            .retryIfResult(Predicates.equalTo(true))
            .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
            .withStopStrategy(StopStrategies.stopAfterDelay(10, TimeUnit.MINUTES))
            .build();
    try {
        retryer.call(callable);
    }
    catch (Exception e) {
        throw new UnableToInterruptJobException(e);
    }

    if (isRunning()) throw new UnableToInterruptJobException("Unable to stop job....");

}
 
开发者ID:andyphillips404,项目名称:awplab-core,代码行数:34,代码来源:AbstractStatusInterruptableJob.java

示例15: CommandQueries

import com.github.rholder.retry.WaitStrategies; //导入依赖的package包/类
CommandQueries(List<QueryRequest> queries, Keyspace keyspace) {
    super(Setter
            .withGroupKey(HystrixCommandGroupKey.Factory.asKey("BatchExecutor"))
            .andThreadPoolPropertiesDefaults(
                    HystrixThreadPoolProperties.Setter()
                            .withCoreSize(threadPoolCoreSize)
                            // Sizing these two based on the thread pool core size
                            .withQueueSizeRejectionThreshold(
                                    threadPoolCoreSize * QUEUE_MULTIPLIER)
                            .withMaxQueueSize(threadPoolCoreSize * QUEUE_MULTIPLIER))
            .andCommandPropertiesDefaults(
                    HystrixCommandProperties.Setter()
                            .withExecutionTimeoutEnabled(false)
                            .withExecutionTimeoutInMilliseconds(timeoutMs)
                            .withRequestLogEnabled(requestLogEnabled)));

    this.queries = queries;
    this.keyspace = keyspace;
    this.graqlExecuteTimer = metricRegistry.timer(name(this.getClass(), "execute"));
    this.attemptMeter = metricRegistry.meter(name(this.getClass(), "attempt"));
    this.retryer = RetryerBuilder.<List<QueryResponse>>newBuilder()
            .retryIfException((throwable) ->
                    throwable instanceof GraknClientException
                            && ((GraknClientException) throwable).isRetriable())
            .retryIfExceptionOfType(ConnectException.class)
            .withWaitStrategy(WaitStrategies.exponentialWait(10, 1, TimeUnit.MINUTES))
            .withStopStrategy(StopStrategies.stopAfterAttempt(maxRetries + 1))
            .withRetryListener(new RetryListener() {
                @Override
                public <V> void onRetry(Attempt<V> attempt) {
                    attemptMeter.mark();
                }
            })
            .build();
}
 
开发者ID:graknlabs,项目名称:grakn,代码行数:36,代码来源:BatchExecutorClient.java


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