org.springframework.retry.policy.SimpleRetryPolicy Java Examples

The following examples show how to use org.springframework.retry.policy.SimpleRetryPolicy. 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: SimpleDemo.java    From retry with Apache License 2.0 8 votes vote down vote up
public static void main(String[] args) throws Exception {
    RetryTemplate template = new RetryTemplate();

    // 策略
    SimpleRetryPolicy policy = new SimpleRetryPolicy();
    policy.setMaxAttempts(2);
    template.setRetryPolicy(policy);

    String result = template.execute(
            new RetryCallback<String, Exception>() {
                @Override
                public String doWithRetry(RetryContext arg0) {
                    throw new NullPointerException();
                }
            }
            ,
            new RecoveryCallback<String>() {
                @Override
                public String recover(RetryContext context) {
                    return "recovery callback";
                }
            }
    );

    LOGGER.info("result: {}", result);
}
 
Example #2
Source File: FeatureFileUtilsImpl.java    From IridiumApplicationTesting with MIT License 8 votes vote down vote up
private List<File> processRemoteUrl(@NotNull final String path) throws IOException {
	final File copy = File.createTempFile("webapptester", ".feature");

	try {
		final RetryTemplate template = new RetryTemplate();
		final SimpleRetryPolicy policy = new SimpleRetryPolicy();
		policy.setMaxAttempts(Constants.URL_COPY_RETRIES);
		template.setRetryPolicy(policy);
		template.execute(context -> {
			FileUtils.copyURLToFile(new URL(path), copy);
			return null;
		});

		return Arrays.asList(copy);
	} catch (final FileNotFoundException ex) {
		/*
			Don't leave an empty file hanging around
		 */
		FileUtils.deleteQuietly(copy);
		throw new RemoteFeatureException("The remote file could not be downloaded."
			+ " Either the URL was invalid, or the path was actually supposed to reference a"
			+ " local file but that file could not be found an so was assumed to be a URL.",  ex);
	}
}
 
Example #3
Source File: FeatureFileImporterImpl.java    From IridiumApplicationTesting with MIT License 8 votes vote down vote up
private String processRemoteUrl(@NotNull final String path) throws IOException {
	final File copy = File.createTempFile("webapptester", ".feature");

	try {
		final RetryTemplate template = new RetryTemplate();
		final SimpleRetryPolicy policy = new SimpleRetryPolicy();
		policy.setMaxAttempts(Constants.URL_COPY_RETRIES);
		template.setRetryPolicy(policy);
		return template.execute(context -> {
			FileUtils.copyURLToFile(new URL(path), copy);
			return FileUtils.readFileToString(copy, Charset.defaultCharset());
		});
	} finally {
		FileUtils.deleteQuietly(copy);
	}
}
 
Example #4
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 #5
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 #6
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 #7
Source File: Application.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Bean
public RetryTemplate retryTemplate() {
    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(5);

    ExponentialRandomBackOffPolicy exponentialRandomBackOffPolicy = new ExponentialRandomBackOffPolicy();
    exponentialRandomBackOffPolicy.setInitialInterval(10);
    exponentialRandomBackOffPolicy.setMultiplier(3);
    exponentialRandomBackOffPolicy.setMaxInterval(5000);

    RetryTemplate template = new RetryTemplate();
    template.setRetryPolicy(retryPolicy);
    template.setBackOffPolicy(exponentialRandomBackOffPolicy);
    template.setThrowLastExceptionOnExhausted(true);

    return template;
}
 
Example #8
Source File: InteractiveQueryService.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve and return a queryable store by name created in the application.
 * @param storeName name of the queryable store
 * @param storeType type of the queryable store
 * @param <T> generic queryable store
 * @return queryable store.
 */
public <T> T getQueryableStore(String storeName, QueryableStoreType<T> storeType) {

	RetryTemplate retryTemplate = new RetryTemplate();

	KafkaStreamsBinderConfigurationProperties.StateStoreRetry stateStoreRetry = this.binderConfigurationProperties.getStateStoreRetry();
	RetryPolicy retryPolicy = new SimpleRetryPolicy(stateStoreRetry.getMaxAttempts());
	FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
	backOffPolicy.setBackOffPeriod(stateStoreRetry.getBackoffPeriod());

	retryTemplate.setBackOffPolicy(backOffPolicy);
	retryTemplate.setRetryPolicy(retryPolicy);

	return retryTemplate.execute(context -> {
		T store = null;

		final Set<KafkaStreams> kafkaStreams = InteractiveQueryService.this.kafkaStreamsRegistry.getKafkaStreams();
		final Iterator<KafkaStreams> iterator = kafkaStreams.iterator();
		Throwable throwable = null;
		while (iterator.hasNext()) {
			try {
				store = iterator.next().store(storeName, storeType);
			}
			catch (InvalidStateStoreException e) {
				// pass through..
				throwable = e;
			}
		}
		if (store != null) {
			return store;
		}
		throw new IllegalStateException("Error when retrieving state store: j " + storeName, throwable);
	});
}
 
Example #9
Source File: FileContentRetrieval.java    From IridiumApplicationTesting with MIT License 6 votes vote down vote up
private String retrieveStringFromRemoteFile(@NotNull final String remoteFileName)  {
	checkArgument(StringUtils.isNoneBlank(remoteFileName));

	File copy = null;
	try {
		copy = File.createTempFile("capabilities", ".tmp");

		final File finalCopy = copy;
		final RetryTemplate template = new RetryTemplate();
		final SimpleRetryPolicy policy = new SimpleRetryPolicy();
		policy.setMaxAttempts(Constants.URL_COPY_RETRIES);
		template.setRetryPolicy(policy);
		template.execute(context -> {
			FileUtils.copyURLToFile(new URL(remoteFileName), finalCopy, TIMEOUT, TIMEOUT);
			return null;
		});

		return retrieveStringFromLocalFile(copy.getAbsolutePath());
	} catch (final IOException ex) {
		throw new ConfigurationException(ex);
	} finally {
		if (copy != null) {
			FileUtils.deleteQuietly(copy);
		}
	}
}
 
Example #10
Source File: DefaultRetryTemplateConverterTest.java    From distributed-lock with MIT License 6 votes vote down vote up
private void assertRetryTemplateConstruction(final RetryTemplate retryTemplate, final long timeout, final long backOff) {
  final var wrapper = PropertyAccessorFactory.forDirectFieldAccess(retryTemplate);

  assertThat(wrapper.getPropertyValue("retryPolicy")).isInstanceOf(CompositeRetryPolicy.class);
  assertThat((RetryPolicy[]) wrapper.getPropertyValue("retryPolicy.policies"))
    .hasSize(2)
    .anyMatch(policy1 -> {
      if (policy1 instanceof TimeoutRetryPolicy) {
        final var timeoutRetryPolicy = (TimeoutRetryPolicy) policy1;
        assertThat(timeoutRetryPolicy.getTimeout()).isEqualTo(timeout);
        return true;
      }
      return false;
    })
    .anyMatch(policy2 -> {
      if (policy2 instanceof SimpleRetryPolicy) {
        final var simpleRetryPolicy = (SimpleRetryPolicy) policy2;
        assertThat(simpleRetryPolicy.getMaxAttempts()).isEqualTo(Integer.MAX_VALUE);
        return true;
      }
      return false;
    });

  assertThat(wrapper.getPropertyValue("backOffPolicy")).isInstanceOf(FixedBackOffPolicy.class);
  assertThat(((FixedBackOffPolicy) wrapper.getPropertyValue("backOffPolicy")).getBackOffPeriod()).isEqualTo(backOff);
}
 
Example #11
Source File: HttpBlockchainEventBroadcasterTest.java    From eventeum with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
    final HttpBroadcasterSettings settings = new HttpBroadcasterSettings();
    settings.setBlockEventsUrl("http://localhost:8082/consumer/block-event");
    settings.setContractEventsUrl("http://localhost:8082/consumer/contract-event");

    RetryTemplate retryTemplate = new RetryTemplate();

    FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
    fixedBackOffPolicy.setBackOffPeriod(3000l);
    retryTemplate.setBackOffPolicy(fixedBackOffPolicy);

    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(3);
    retryTemplate.setRetryPolicy(retryPolicy);

    underTest = new HttpBlockchainEventBroadcaster(settings, retryTemplate);
}
 
Example #12
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 #13
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 #14
Source File: JpaDeploymentManagement.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
private static RetryTemplate createRetryTemplate() {
    final RetryTemplate template = new RetryTemplate();

    final FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    backOffPolicy.setBackOffPeriod(Constants.TX_RT_DELAY);
    template.setBackOffPolicy(backOffPolicy);

    final SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(Constants.TX_RT_MAX,
            Collections.singletonMap(ConcurrencyFailureException.class, true));
    template.setRetryPolicy(retryPolicy);

    return template;
}
 
Example #15
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 #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: ProjectGenerationStatPublisherTests.java    From initializr with Apache License 2.0 5 votes vote down vote up
@Test
void fatalErrorOnlyLogs() {
	ProjectRequest request = createProjectRequest();
	ProjectGeneratedEvent event = new ProjectGeneratedEvent(request, this.metadata);
	this.retryTemplate.setRetryPolicy(new SimpleRetryPolicy(2, Collections.singletonMap(Exception.class, true)));

	this.mockServer.expect(requestTo("https://example.com/elastic/initializr/request"))
			.andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));

	this.mockServer.expect(requestTo("https://example.com/elastic/initializr/request"))
			.andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));

	this.statPublisher.handleEvent(event);
	this.mockServer.verify();
}
 
Example #19
Source File: MailServiceImpl.java    From cymbal with Apache License 2.0 5 votes vote down vote up
public MailServiceImpl() {
    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(MAIL_MAX_ATTEMPTS);
    retryTemplate.setRetryPolicy(retryPolicy);

    // 失败后补偿策略
    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    backOffPolicy.setBackOffPeriod(MAIL_BACKOFF_PERIOD);
    retryTemplate.setBackOffPolicy(backOffPolicy);
}
 
Example #20
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 #21
Source File: AutoCreateTopicDisabledTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Test
public void testAutoCreateTopicDisabledFailsOnProducerIfTopicNonExistentOnBroker()
		throws Throwable {

	KafkaProperties kafkaProperties = new TestKafkaProperties();
	kafkaProperties.setBootstrapServers(Collections
			.singletonList(embeddedKafka.getEmbeddedKafka().getBrokersAsString()));

	KafkaBinderConfigurationProperties configurationProperties = new KafkaBinderConfigurationProperties(
			kafkaProperties);
	// disable auto create topic on the binder.
	configurationProperties.setAutoCreateTopics(false);
	// reduce the wait time on the producer blocking operations.
	configurationProperties.getConfiguration().put("max.block.ms", "3000");

	KafkaTopicProvisioner provisioningProvider = new KafkaTopicProvisioner(
			configurationProperties, kafkaProperties);
	SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy(1);
	final RetryTemplate metadataRetryOperations = new RetryTemplate();
	metadataRetryOperations.setRetryPolicy(simpleRetryPolicy);
	provisioningProvider.setMetadataRetryOperations(metadataRetryOperations);

	KafkaMessageChannelBinder binder = new KafkaMessageChannelBinder(
			configurationProperties, provisioningProvider);

	final String testTopicName = "nonExistent" + System.currentTimeMillis();

	ExtendedProducerProperties<KafkaProducerProperties> properties = new ExtendedProducerProperties<>(
			new KafkaProducerProperties());

	expectedException.expect(BinderException.class);
	expectedException.expectCause(isA(UnknownTopicOrPartitionException.class));

	binder.bindProducer(testTopicName, new DirectChannel(), properties);

}
 
Example #22
Source File: RetryInterceptor.java    From mica with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static RetryTemplate createRetryTemplate(RetryPolicy policy) {
	RetryTemplate template = new RetryTemplate();
	// 重试策略
	SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
	retryPolicy.setMaxAttempts(policy.getMaxAttempts());
	// 设置间隔策略
	FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
	backOffPolicy.setBackOffPeriod(policy.getSleepMillis());
	template.setRetryPolicy(retryPolicy);
	template.setBackOffPolicy(backOffPolicy);
	return template;
}
 
Example #23
Source File: RetryExampleApplication.java    From blog-examples with Apache License 2.0 5 votes vote down vote up
@Bean
public RetryTemplate retryTemplate() {
    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(5);

    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    backOffPolicy.setBackOffPeriod(1500); // 1.5 seconds

    RetryTemplate template = new RetryTemplate();
    template.setRetryPolicy(retryPolicy);
    template.setBackOffPolicy(backOffPolicy);

    return template;
}
 
Example #24
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 #25
Source File: ClusterScaleProcessServiceImpl.java    From cymbal with Apache License 2.0 5 votes vote down vote up
public ClusterScaleProcessServiceImpl() {
    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(ENLARGE_MAX_ATTEMPTS);
    retryTemplate.setRetryPolicy(retryPolicy);

    // 失败后补偿策略
    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    backOffPolicy.setBackOffPeriod(MIGRATE_BACKOFF_PERIOD);
    retryTemplate.setBackOffPolicy(backOffPolicy);
}
 
Example #26
Source File: RetriableLockTest.java    From distributed-lock with MIT License 5 votes vote down vote up
@Test
public void shouldRetryWhenFirstAttemptIsNotSuccessful() {
  when(lock.acquire(anyList(), anyString(), anyLong()))
    .thenReturn(null)
    .thenReturn("abc");

  final var retryTemplate = new RetryTemplate();
  retryTemplate.setRetryPolicy(new SimpleRetryPolicy(2));

  final var retriableLock = new RetriableLock(lock, retryTemplate);
  final var token = retriableLock.acquire(List.of("key"), "defaultStore", 1000L);

  assertThat(token).isEqualTo("abc");
  verify(lock, times(2)).acquire(anyList(), anyString(), anyLong());
}
 
Example #27
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 #28
Source File: RetryPolicy.java    From mica with GNU Lesser General Public License v3.0 4 votes vote down vote up
public RetryPolicy(@Nullable Predicate<ResponseSpec> respPredicate) {
	this(SimpleRetryPolicy.DEFAULT_MAX_ATTEMPTS, 0L, respPredicate);
}
 
Example #29
Source File: CuratorKafkaMonitor.java    From Kafdrop with Apache License 2.0 4 votes vote down vote up
public CuratorKafkaMonitor(CuratorFramework curatorFramework,
                           CuratorKafkaMonitorProperties properties,
                           ObjectMapper objectMapper) throws Exception
{
   this.curatorFramework = curatorFramework;
   this.properties = properties;
   this.objectMapper = objectMapper;

   try
   {
      kafkaVersion = new Version(properties.getKafkaVersion());
   }
   catch (Exception ex)
   {
      throw new IllegalStateException("Invalid kafka version: " + properties.getKafkaVersion(), ex);
   }

   threadPool = new ForkJoinPool(properties.getThreadPoolSize());

   FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
   backOffPolicy.setBackOffPeriod(properties.getRetry().getBackoffMillis());

   final SimpleRetryPolicy retryPolicy =
      new SimpleRetryPolicy(properties.getRetry().getMaxAttempts(),
                            ImmutableMap.of(InterruptedException.class, false,
                                            Exception.class, true));

   retryTemplate = new RetryTemplate();
   retryTemplate.setBackOffPolicy(backOffPolicy);
   retryTemplate.setRetryPolicy(retryPolicy);

   cacheInitCounter.set(4);

   brokerPathCache = new PathChildrenCache(curatorFramework, ZkUtils.BrokerIdsPath(), true);
   brokerPathCache.getListenable().addListener(new BrokerListener());
   brokerPathCache.getListenable().addListener((f, e) -> {
      if (e.getType() == PathChildrenCacheEvent.Type.INITIALIZED)
      {
         cacheInitCounter.decrementAndGet();
         LOG.info("Broker cache initialized");
      }
   });
   brokerPathCache.start(StartMode.POST_INITIALIZED_EVENT);

   topicConfigPathCache = new PathChildrenCache(curatorFramework, ZkUtils.TopicConfigPath(), true);
   topicConfigPathCache.getListenable().addListener((f, e) -> {
      if (e.getType() == PathChildrenCacheEvent.Type.INITIALIZED)
      {
         cacheInitCounter.decrementAndGet();
         LOG.info("Topic configuration cache initialized");
      }
   });
   topicConfigPathCache.start(StartMode.POST_INITIALIZED_EVENT);

   topicTreeCache = new TreeCache(curatorFramework, ZkUtils.BrokerTopicsPath());
   topicTreeCache.getListenable().addListener((client, event) -> {
      if (event.getType() == TreeCacheEvent.Type.INITIALIZED)
      {
         cacheInitCounter.decrementAndGet();
         LOG.info("Topic tree cache initialized");
      }
   });
   topicTreeCache.start();

   consumerTreeCache = new TreeCache(curatorFramework, ZkUtils.ConsumersPath());
   consumerTreeCache.getListenable().addListener((client, event) -> {
      if (event.getType() == TreeCacheEvent.Type.INITIALIZED)
      {
         cacheInitCounter.decrementAndGet();
         LOG.info("Consumer tree cache initialized");
      }
   });
   consumerTreeCache.start();

   controllerNodeCache = new NodeCache(curatorFramework, ZkUtils.ControllerPath());
   controllerNodeCache.getListenable().addListener(this::updateController);
   controllerNodeCache.start(true);
   updateController();
}
 
Example #30
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();
}