org.springframework.retry.backoff.ExponentialBackOffPolicy Java Examples

The following examples show how to use org.springframework.retry.backoff.ExponentialBackOffPolicy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JobKickoffTask.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param runAsUserEnabled                   Flag that tells if job should be run as user specified in the request
 * @param userCreationEnabled                Flag that tells if the user specified should be created
 * @param executor                           An executor object used to run jobs
 * @param hostname                           Hostname for the node the job is running on
 * @param registry                           The metrics registry to use
 * @param jobDirectoryManifestCreatorService The manifest creator service
 */
public JobKickoffTask(
    final boolean runAsUserEnabled,
    final boolean userCreationEnabled,
    @NotNull final Executor executor,
    @NotNull final String hostname,
    @NotNull final MeterRegistry registry,
    final JobDirectoryManifestCreatorService jobDirectoryManifestCreatorService
) {
    super(registry);
    this.isRunAsUserEnabled = runAsUserEnabled;
    this.isUserCreationEnabled = userCreationEnabled;
    this.executor = executor;
    this.hostname = hostname;
    this.jobDirectoryManifestCreatorService = jobDirectoryManifestCreatorService;
    this.retryTemplate = new RetryTemplate();
    this.retryTemplate.setBackOffPolicy(new ExponentialBackOffPolicy());
}
 
Example #2
Source File: DataServiceRetryAspect.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param dataServiceRetryProperties retry properties
 */
public DataServiceRetryAspect(final DataServiceRetryProperties dataServiceRetryProperties) {
    this.retryTemplate = new RetryTemplate();
    this.retryTemplate.setRetryPolicy(
        new SimpleRetryPolicy(
            dataServiceRetryProperties.getNoOfRetries(),
            new ImmutableMap.Builder<Class<? extends Throwable>, Boolean>()
                .put(CannotGetJdbcConnectionException.class, true)
                .put(CannotAcquireLockException.class, true)
                .put(DeadlockLoserDataAccessException.class, true)
                .put(OptimisticLockingFailureException.class, true)
                .put(PessimisticLockingFailureException.class, true)
                .put(ConcurrencyFailureException.class, true)
                // Will this work for cases where the write queries timeout on the client?
                .put(QueryTimeoutException.class, true)
                .put(TransientDataAccessResourceException.class, true)
                .put(JpaSystemException.class, true)
                .build()
        )
    );
    final ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
    backOffPolicy.setInitialInterval(dataServiceRetryProperties.getInitialInterval());
    backOffPolicy.setMaxInterval(dataServiceRetryProperties.getMaxInterval());
    this.retryTemplate.setBackOffPolicy(backOffPolicy);
}
 
Example #3
Source File: KafkaTopicProvisioner.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
	if (this.metadataRetryOperations == null) {
		RetryTemplate retryTemplate = new RetryTemplate();

		SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
		simpleRetryPolicy.setMaxAttempts(10);
		retryTemplate.setRetryPolicy(simpleRetryPolicy);

		ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
		backOffPolicy.setInitialInterval(100);
		backOffPolicy.setMultiplier(2);
		backOffPolicy.setMaxInterval(1000);
		retryTemplate.setBackOffPolicy(backOffPolicy);
		this.metadataRetryOperations = retryTemplate;
	}
}
 
Example #4
Source File: ApisAutoConfiguration.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Get RetryTemplate.
 *
 * @param retryProperties The http retry properties to use
 * @return The retry template to use
 */
@Bean
@ConditionalOnMissingBean(name = "genieRetryTemplate")
public RetryTemplate genieRetryTemplate(final RetryProperties retryProperties) {
    final RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setRetryPolicy(
        new SimpleRetryPolicy(
            retryProperties.getNoOfRetries(),
            Collections.singletonMap(Exception.class, true)
        )
    );
    final ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
    backOffPolicy.setInitialInterval(retryProperties.getInitialInterval());
    backOffPolicy.setMaxInterval(retryProperties.getMaxInterval());
    retryTemplate.setBackOffPolicy(backOffPolicy);
    return retryTemplate;
}
 
Example #5
Source File: RabbitMQConfig.java    From micro-service with MIT License 5 votes vote down vote up
@Bean()
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public RabbitTemplate rabbitTemplate() {
	
	ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
	backOffPolicy.setInitialInterval(500);
	backOffPolicy.setMultiplier(10.0);
	backOffPolicy.setMaxInterval(10000);
	
	RetryTemplate retryTemplate = new RetryTemplate();
	retryTemplate.setBackOffPolicy(backOffPolicy);
	
	RabbitTemplate template = new RabbitTemplate(connectionFactory());
	template.setRetryTemplate(retryTemplate);
	template.setChannelTransacted(false);
	
	template.setConfirmCallback(new ConfirmCallback() {
		@Override
		public void confirm(CorrelationData correlationData, boolean ack, String cause) {
			if(ack) {
				logger.info("发送消息成功, correlationId={}", correlationData.getId());
			} else {
				logger.info("发送消息失败, correlationId={}, cause={}", correlationData.getId(), cause);
			}
		}
	});
	
	return template;
}
 
Example #6
Source File: ExponentialBackoffRetryFactory.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public BackOffPolicy createBackOffPolicy(String service) {
    ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
    exponentialBackOffPolicy.setInitialInterval(1000);
    exponentialBackOffPolicy.setMultiplier(2);
    exponentialBackOffPolicy.setMaxInterval(10000);
    return exponentialBackOffPolicy;
}
 
Example #7
Source File: ConnectionRetryConfigTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testBackOffPolicyIsExponential() {
  List<Long> sleeps = newArrayList();
  ExponentialBackOffPolicy fakeBackOff = this.backOffPolicy.withSleeper(sleeps::add);
  BackOffContext context = fakeBackOff.start(null);
  for (int i = 0; i < 11; i++) {
    fakeBackOff.backOff(context);
  }
  assertEquals(
      asList(
          1000L, 2000L, 4000L, 8000L, 16000L, 32000L, 64000L, 128000L, 256000L, 300000L, 300000L),
      sleeps);
}
 
Example #8
Source File: InitializrStatsAutoConfigurationTests.java    From initializr with Apache License 2.0 5 votes vote down vote up
@Bean
RetryTemplate statsRetryTemplate() {
	RetryTemplate retryTemplate = new RetryTemplate();
	ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
	backOffPolicy.setMultiplier(10);
	retryTemplate.setBackOffPolicy(backOffPolicy);
	return retryTemplate;
}
 
Example #9
Source File: InitializrStatsAutoConfigurationTests.java    From initializr with Apache License 2.0 5 votes vote down vote up
@Test
void statsRetryTemplateConditionalOnMissingBean() {
	this.contextRunner.withUserConfiguration(CustomStatsRetryTemplateConfiguration.class)
			.withPropertyValues("initializr.stats.elastic.uri=http://localhost:9200").run((context) -> {
				assertThat(context).hasSingleBean(RetryTemplate.class);
				RetryTemplate retryTemplate = context.getBean(RetryTemplate.class);
				ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils
						.getField(retryTemplate, "backOffPolicy");
				assertThat(backOffPolicy.getMultiplier()).isEqualTo(10);
			});
}
 
Example #10
Source File: InitializrStatsAutoConfiguration.java    From initializr with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "statsRetryTemplate")
RetryTemplate statsRetryTemplate() {
	RetryTemplate retryTemplate = new RetryTemplate();
	ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
	backOffPolicy.setInitialInterval(3000L);
	backOffPolicy.setMultiplier(3);
	SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(this.statsProperties.getElastic().getMaxAttempts(),
			Collections.singletonMap(Exception.class, true));
	retryTemplate.setBackOffPolicy(backOffPolicy);
	retryTemplate.setRetryPolicy(retryPolicy);
	return retryTemplate;
}
 
Example #11
Source File: JerseyClientRetryTemplateConfig.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Bean
public RetryTemplate jerseyClientRetryTemplate() {
    RetryTemplate retryTemplate = new RetryTemplate();
    ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
    exponentialBackOffPolicy.setInitialInterval(INITIAL_BACKOFF_IN_MILLIS);
    exponentialBackOffPolicy.setMultiplier(2.0);
    exponentialBackOffPolicy.setMaxInterval(MAX_BACKOFF_IN_MILLIS);
    retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);
    retryTemplate.setRetryPolicy(new JerseyClientRetryPolicy());
    return retryTemplate;
}
 
Example #12
Source File: RetryConfig.java    From batchers with Apache License 2.0 5 votes vote down vote up
public RetryTemplate createRetryTemplate() {
    Map<Class<? extends Throwable>, Boolean> exceptions = new HashMap<>();
    exceptions.put(TaxWebServiceNonFatalException.class, true);

    RetryTemplate template = new RetryTemplate();
    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(maxAttempts, exceptions);
    template.setRetryPolicy(retryPolicy);

    ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
    backOffPolicy.setInitialInterval(initialInterval);
    template.setBackOffPolicy(backOffPolicy);

    return template;
}
 
Example #13
Source File: RabbitAutoConfiguration.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private RetryTemplate createRetryTemplate(RabbitProperties.Retry properties) {
    RetryTemplate template = new RetryTemplate();
    SimpleRetryPolicy policy = new SimpleRetryPolicy();
    policy.setMaxAttempts(properties.getMaxAttempts());
    template.setRetryPolicy(policy);
    ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
    backOffPolicy.setInitialInterval(properties.getInitialInterval());
    backOffPolicy.setMultiplier(properties.getMultiplier());
    backOffPolicy.setMaxInterval(properties.getMaxInterval());
    template.setBackOffPolicy(backOffPolicy);
    return template;
}
 
Example #14
Source File: RabbitMQConfiguration.java    From cukes with Apache License 2.0 5 votes vote down vote up
@Bean
RabbitTemplate rabbitTemplate(org.springframework.amqp.rabbit.connection.ConnectionFactory  cf,
                              ObjectMapper mapper) {
    RabbitTemplate template = new RabbitTemplate(cf);
    template.setExchange(EXCHANGE_NAME);
    RetryTemplate retry = new RetryTemplate();
    ExponentialBackOffPolicy backOff = new ExponentialBackOffPolicy();
    backOff.setInitialInterval(1000);
    backOff.setMultiplier(1.5);
    backOff.setMaxInterval(60000);
    retry.setBackOffPolicy(backOff);
    template.setRetryTemplate(retry);
    template.setMessageConverter(new Jackson2JsonMessageConverter(mapper));
    return template;
}
 
Example #15
Source File: OTXConnection.java    From OTX-Java-SDK with Apache License 2.0 5 votes vote down vote up
/**
 * Internal API to configure RestTemplate
 *
 * @param apiKey - API key to configure authorization header
 */
private void configureRestTemplate(String apiKey) {
    ClientHttpRequestFactory requestFactory = HTTPConfig.createRequestFactory(apiKey);
    restTemplate = new RestTemplate(requestFactory);
    retryTemplate = new RetryTemplate();
    retryTemplate.setBackOffPolicy(new ExponentialBackOffPolicy());
}
 
Example #16
Source File: AggregateCounterSinkStoreConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Bean
public RetryOperations retryOperations() {
	RetryTemplate retryTemplate = new RetryTemplate();
	retryTemplate.setRetryPolicy(new SimpleRetryPolicy(3,
			Collections.<Class<? extends Throwable>, Boolean>singletonMap(RedisConnectionFailureException.class, true)));
	ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
	backOffPolicy.setInitialInterval(1000L);
	backOffPolicy.setMaxInterval(1000L);
	backOffPolicy.setMultiplier(2);
	retryTemplate.setBackOffPolicy(backOffPolicy);
	return retryTemplate;
}
 
Example #17
Source File: FieldValueCounterSinkStoreConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Bean
public RetryOperations retryOperations() {
	RetryTemplate retryTemplate = new RetryTemplate();
	retryTemplate.setRetryPolicy(new SimpleRetryPolicy(3, Collections.<Class<? extends Throwable>, Boolean>singletonMap(RedisConnectionFailureException.class, true)));
	ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
	backOffPolicy.setInitialInterval(1000L);
	backOffPolicy.setMaxInterval(1000L);
	backOffPolicy.setMultiplier(2);
	retryTemplate.setBackOffPolicy(backOffPolicy);
	return retryTemplate;
}
 
Example #18
Source File: JobStatusWebhookEventListener.java    From piper with Apache License 2.0 5 votes vote down vote up
private RetryTemplate createRetryTemplate (Accessor aWebhook) {
  MapObject retryParams = aWebhook.get("retry",MapObject.class,new MapObject());
  RetryTemplate retryTemplate = new RetryTemplate();
  ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
  backOffPolicy.setInitialInterval(retryParams.getDuration("initialInterval", "2s").toMillis());
  backOffPolicy.setMaxInterval(retryParams.getDuration("maxInterval", "30s").toMillis());
  backOffPolicy.setMultiplier(retryParams.getDouble("multiplier",2.0));
  retryTemplate.setBackOffPolicy(backOffPolicy);
  SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
  retryPolicy.setMaxAttempts(retryParams.getInteger("maxAttempts", 5));
  retryTemplate.setRetryPolicy(retryPolicy);
  return retryTemplate;
}
 
Example #19
Source File: RetryServiceImpl.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
@Override
public RetryTemplate getRetryTemplate() {
	final SimpleRetryPolicy policy = new SimpleRetryPolicy();
	policy.setMaxAttempts(Constants.WEBDRIVER_ACTION_RETRIES);

	final ExponentialBackOffPolicy backoff = new ExponentialBackOffPolicy();
	backoff.setInitialInterval(RETRY_INTERVAL);

	final RetryTemplate template = new RetryTemplate();
	template.setRetryPolicy(policy);
	template.setBackOffPolicy(backoff);
	return template;
}
 
Example #20
Source File: CMSClient.java    From oneops with Apache License 2.0 5 votes vote down vote up
@Bean
protected RetryTemplate getRetryTemplate(@Value("${controller.retryCount:3}") int retryCount, @Value("${controller.intial_delay:1000}") int initialDelay, @Value("${controller.maxInterval:10000}") int maxInterval) {
    RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setRetryPolicy(new SimpleRetryPolicy(retryCount, Collections.singletonMap(RestClientException.class, true)));
    ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
    backOffPolicy.setInitialInterval(initialDelay);
    backOffPolicy.setMaxInterval(maxInterval);
    retryTemplate.setBackOffPolicy(backOffPolicy);
    retryTemplate.setThrowLastExceptionOnExhausted(true);


    retryTemplate.registerListener(new DefaultListenerSupport());

    return retryTemplate;
}
 
Example #21
Source File: RabbitBinderModuleTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 4 votes vote down vote up
@Test
public void testParentConnectionFactoryNotInheritedByCustomizedBindersAndProducerRetryBootProperties() {
	List<String> params = new ArrayList<>();
	params.add("--spring.cloud.stream.input.binder=custom");
	params.add("--spring.cloud.stream.output.binder=custom");
	params.add("--spring.cloud.stream.binders.custom.type=rabbit");
	params.add("--spring.cloud.stream.binders.custom.environment.foo=bar");
	params.add("--server.port=0");
	params.add("--spring.rabbitmq.template.retry.enabled=true");
	params.add("--spring.rabbitmq.template.retry.maxAttempts=2");
	params.add("--spring.rabbitmq.template.retry.initial-interval=1000");
	params.add("--spring.rabbitmq.template.retry.multiplier=1.1");
	params.add("--spring.rabbitmq.template.retry.max-interval=3000");
	context = new SpringApplicationBuilder(SimpleProcessor.class)
			.web(WebApplicationType.NONE)
			.run(params.toArray(new String[params.size()]));
	BinderFactory binderFactory = context.getBean(BinderFactory.class);
	// @checkstyle:off
	@SuppressWarnings("unchecked")
	Binder<MessageChannel, ExtendedConsumerProperties<RabbitConsumerProperties>, ExtendedProducerProperties<RabbitProducerProperties>> binder = (Binder<MessageChannel, ExtendedConsumerProperties<RabbitConsumerProperties>, ExtendedProducerProperties<RabbitProducerProperties>>) binderFactory
			.getBinder(null, MessageChannel.class);
	// @checkstyle:on
	assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class);
	DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
	ConnectionFactory binderConnectionFactory = (ConnectionFactory) binderFieldAccessor
			.getPropertyValue("connectionFactory");
	ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class);
	assertThat(binderConnectionFactory).isNotSameAs(connectionFactory);
	CompositeHealthContributor bindersHealthIndicator = context
			.getBean("bindersHealthContributor", CompositeHealthContributor.class);
	assertThat(bindersHealthIndicator);

	RabbitHealthIndicator indicator = (RabbitHealthIndicator) bindersHealthIndicator.getContributor("custom");
	assertThat(indicator).isNotNull();
	assertThat(indicator.health().getStatus()).isEqualTo(Status.UP);
	String name = UUID.randomUUID().toString();
	Binding<MessageChannel> binding = binder.bindProducer(name, new DirectChannel(),
			new ExtendedProducerProperties<>(new RabbitProducerProperties()));
	RetryTemplate template = TestUtils.getPropertyValue(binding,
			"lifecycle.amqpTemplate.retryTemplate", RetryTemplate.class);
	assertThat(template).isNotNull();
	SimpleRetryPolicy retryPolicy = TestUtils.getPropertyValue(template,
			"retryPolicy", SimpleRetryPolicy.class);
	ExponentialBackOffPolicy backOff = TestUtils.getPropertyValue(template,
			"backOffPolicy", ExponentialBackOffPolicy.class);
	assertThat(retryPolicy.getMaxAttempts()).isEqualTo(2);
	assertThat(backOff.getInitialInterval()).isEqualTo(1000L);
	assertThat(backOff.getMultiplier()).isEqualTo(1.1);
	assertThat(backOff.getMaxInterval()).isEqualTo(3000L);
	binding.unbind();
	new RabbitAdmin(rabbitTestSupport.getResource()).deleteExchange(name);
	context.close();
}