Java Code Examples for org.springframework.retry.support.RetryTemplate

The following examples show how to use org.springframework.retry.support.RetryTemplate. These examples are extracted from open source projects. 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 Project: mica   Source File: RetryInterceptor.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Response intercept(Chain chain) throws IOException {
	Request request = chain.request();
	RetryTemplate template = createRetryTemplate(retryPolicy);
	return template.execute(context -> {
		Response response = chain.proceed(request);
		// 结果集校验
		Predicate<ResponseSpec> respPredicate = retryPolicy.getRespPredicate();
		if (respPredicate == null) {
			return response;
		}
		// copy 一份 body
		ResponseBody body = response.peekBody(Long.MAX_VALUE);
		try (HttpResponse httpResponse = new HttpResponse(response)) {
			if (respPredicate.test(httpResponse)) {
				throw new IOException("Http Retry ResponsePredicate test Failure.");
			}
		}
		return response.newBuilder().body(body).build();
	});
}
 
Example 2
Source Project: genie   Source File: DataServiceRetryAspect.java    License: 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 Project: retry   Source File: SimpleDemo.java    License: Apache License 2.0 6 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 4
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 5
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 6
Source Project: IridiumApplicationTesting   Source File: FeatureFileUtilsImpl.java    License: MIT License 6 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 7
Source Project: IridiumApplicationTesting   Source File: FileContentRetrieval.java    License: 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 8
@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 9
Source Project: genie   Source File: ApisAutoConfiguration.java    License: 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 10
Source Project: genie   Source File: JobKickoffTask.java    License: 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 11
public MetadataSyncJob( SystemSettingManager systemSettingManager, RetryTemplate retryTemplate,
    SynchronizationManager synchronizationManager, MetadataSyncPreProcessor metadataSyncPreProcessor,
    MetadataSyncPostProcessor metadataSyncPostProcessor, MetadataSyncService metadataSyncService,
    MetadataRetryContext metadataRetryContext )
{

    checkNotNull( systemSettingManager );
    checkNotNull( retryTemplate );
    checkNotNull( synchronizationManager );
    checkNotNull( metadataSyncPreProcessor );
    checkNotNull( metadataSyncPostProcessor );
    checkNotNull( metadataSyncService );
    checkNotNull( metadataRetryContext );

    this.systemSettingManager = systemSettingManager;
    this.retryTemplate = retryTemplate;
    this.synchronizationManager = synchronizationManager;
    this.metadataSyncPreProcessor = metadataSyncPreProcessor;
    this.metadataSyncPostProcessor = metadataSyncPostProcessor;
    this.metadataSyncService = metadataSyncService;
    this.metadataRetryContext = metadataRetryContext;
}
 
Example 12
Source Project: spring-cloud-stream   Source File: RetryTemplateTests.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Test
public void testSpecificCustomRetryTemplate() throws Exception {
	ApplicationContext context = new SpringApplicationBuilder(
			SpecificCustomRetryTemplateConfiguration.class)
					.web(WebApplicationType.NONE).run("--spring.jmx.enabled=false",
							"--spring.cloud.stream.bindings.input.consumer.retry-template-name=retryTemplateTwo");

	RetryTemplate retryTemplateTwo = context.getBean("retryTemplateTwo",
			RetryTemplate.class);
	BindingServiceProperties bindingServiceProperties = context
			.getBean(BindingServiceProperties.class);
	ConsumerProperties consumerProperties = bindingServiceProperties
			.getConsumerProperties("input");
	AbstractBinder binder = context.getBean(AbstractBinder.class);

	Method m = AbstractBinder.class.getDeclaredMethod("buildRetryTemplate",
			ConsumerProperties.class);
	m.setAccessible(true);
	RetryTemplate retryTemplate = (RetryTemplate) m.invoke(binder,
			consumerProperties);
	assertThat(retryTemplate).isEqualTo(retryTemplateTwo);
}
 
Example 13
private RetryTemplate createRetryTemplate(String serviceName, HttpRequest request,
		LoadBalancedRetryPolicy retryPolicy) {
	RetryTemplate template = new RetryTemplate();
	BackOffPolicy backOffPolicy = this.lbRetryFactory
			.createBackOffPolicy(serviceName);
	template.setBackOffPolicy(
			backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy);
	template.setThrowLastExceptionOnExhausted(true);
	RetryListener[] retryListeners = this.lbRetryFactory
			.createRetryListeners(serviceName);
	if (retryListeners != null && retryListeners.length != 0) {
		template.setListeners(retryListeners);
	}
	template.setRetryPolicy(!this.lbProperties.isEnabled() || retryPolicy == null
			? new NeverRetryPolicy() : new InterceptorRetryPolicy(request,
					retryPolicy, this.loadBalancer, serviceName));
	return template;
}
 
Example 14
Source Project: mica   Source File: RetryInterceptor.java    License: 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 15
Source Project: enode   Source File: KafkaCommandConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public KafkaMessageListenerContainer kafkaMessageListenerContainer(KafkaCommandListener commandListener, RetryTemplate retryTemplate) {
    ContainerProperties properties = new ContainerProperties(COMMAND_TOPIC);
    properties.setGroupId(DEFAULT_CONSUMER_GROUP);
    RetryingMessageListenerAdapter listenerAdapter = new RetryingMessageListenerAdapter(commandListener, retryTemplate);
    properties.setMessageListener(listenerAdapter);
    properties.setMissingTopicsFatal(false);
    properties.setAckMode(ContainerProperties.AckMode.MANUAL);
    return new KafkaMessageListenerContainer<>(consumerFactory(), properties);
}
 
Example 16
Source Project: enode   Source File: KafkaEventConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public KafkaMessageListenerContainer domainEventListenerContainer(KafkaDomainEventListener domainEventListener, RetryTemplate retryTemplate) {
    ContainerProperties properties = new ContainerProperties(QueueProperties.EVENT_TOPIC);
    properties.setGroupId(QueueProperties.DEFAULT_PRODUCER_GROUP);
    RetryingMessageListenerAdapter listenerAdapter = new RetryingMessageListenerAdapter(domainEventListener, retryTemplate);
    properties.setMessageListener(listenerAdapter);
    properties.setMissingTopicsFatal(false);
    properties.setAckMode(ContainerProperties.AckMode.MANUAL);
    return new KafkaMessageListenerContainer<>(consumerFactory(), properties);
}
 
Example 17
@Bean
RetryTemplate statsRetryTemplate() {
	RetryTemplate retryTemplate = new RetryTemplate();
	ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
	backOffPolicy.setMultiplier(10);
	retryTemplate.setBackOffPolicy(backOffPolicy);
	return retryTemplate;
}
 
Example 18
Source Project: enode   Source File: KafkaEventConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public KafkaMessageListenerContainer publishableExceptionListenerContainer(KafkaPublishableExceptionListener publishableExceptionListener, RetryTemplate retryTemplate) {
    ContainerProperties properties = new ContainerProperties(QueueProperties.EXCEPTION_TOPIC);
    properties.setGroupId(QueueProperties.DEFAULT_PRODUCER_GROUP);
    RetryingMessageListenerAdapter listenerAdapter = new RetryingMessageListenerAdapter(publishableExceptionListener, retryTemplate);
    properties.setMessageListener(listenerAdapter);
    properties.setMissingTopicsFatal(false);
    properties.setAckMode(ContainerProperties.AckMode.MANUAL);
    return new KafkaMessageListenerContainer<>(consumerFactory(), properties);
}
 
Example 19
Source Project: summerframework   Source File: RabbitAutoConfiguration.java    License: 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 20
Source Project: genie   Source File: JobCompletionService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param dataServices      The {@link DataServices} instance to use
 * @param jobArchiveService An implementation of {@link JobArchiveService}
 * @param genieWorkingDir   The working directory where all job directories are created.
 * @param mailServiceImpl   An implementation of the mail service.
 * @param registry          The metrics registry to use
 * @param jobsProperties    The properties relating to running jobs
 * @param retryTemplate     Retry template for retrying remote calls
 * @throws GenieException if there is a problem
 */
public JobCompletionService(
    final DataServices dataServices,
    final JobArchiveService jobArchiveService,
    final Resource genieWorkingDir,
    final MailService mailServiceImpl,
    final MeterRegistry registry,
    final JobsProperties jobsProperties,
    @NotNull final RetryTemplate retryTemplate
) throws GenieException {
    this.persistenceService = dataServices.getPersistenceService();
    this.jobArchiveService = jobArchiveService;
    this.mailServiceImpl = mailServiceImpl;
    this.deleteDependencies = jobsProperties.getCleanup().isDeleteDependencies();
    this.runAsUserEnabled = jobsProperties.getUsers().isRunAsUserEnabled();

    this.executor = new DefaultExecutor();
    this.executor.setStreamHandler(new PumpStreamHandler(null, null));

    try {
        this.baseWorkingDir = genieWorkingDir.getFile();
    } catch (IOException gse) {
        throw new GenieServerException("Could not load the base path from resource", gse);
    }

    // Set up the metrics
    this.registry = registry;
    // Retry template
    this.retryTemplate = retryTemplate;
    this.jobCompletionHandlingLocksMap = new ConcurrentHashMap<>();
}
 
Example 21
@Bean
public RetryTemplate eternalRetryTemplate() {
    RetryTemplate retryTemplate = new RetryTemplate();

    FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
    fixedBackOffPolicy.setBackOffPeriod(DEFAULT_BACKOFF_TIME);
    retryTemplate.setBackOffPolicy(fixedBackOffPolicy);

    AlwaysRetryPolicy retryPolicy = new AlwaysRetryPolicy();
    retryTemplate.setRetryPolicy(retryPolicy);

    return retryTemplate;
}
 
Example 22
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(name=BROADCASTER_PROPERTY, havingValue="HTTP")
public BlockchainEventBroadcaster httpBlockchainEventBroadcaster(HttpBroadcasterSettings settings, RetryTemplate retryTemplate) {
    final BlockchainEventBroadcaster broadcaster =
            new HttpBlockchainEventBroadcaster(settings, retryTemplate);

    return onlyOnceWrap(broadcaster);
}
 
Example 23
Source Project: eventeum   Source File: DefaultSubscriptionServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    when(mockChainServicesContainer.getNodeServices(
            Constants.DEFAULT_NODE_NAME)).thenReturn(mockNodeServices);
    when(mockChainServicesContainer.getNodeNames()).thenReturn(
            Collections.singletonList(Constants.DEFAULT_NODE_NAME));
    when(mockNodeServices.getBlockchainService()).thenReturn(mockBlockchainService);

    mockRetryTemplate = new RetryTemplate();

    underTest = new DefaultSubscriptionService(mockChainServicesContainer,
            mockRepo, mockFilterBroadcaster, new DummyAsyncTaskService(),
            Arrays.asList(mockBlockListener1, mockBlockListener2),
            Arrays.asList(mockEventListener1, mockEventListener2),mockRetryTemplate);
}
 
Example 24
public SpringRetryCircuitBreaker(String id,
		SpringRetryConfigBuilder.SpringRetryConfig config,
		Optional<Customizer<RetryTemplate>> retryTemplateCustomizer) {
	this.id = id;
	this.config = config;
	this.retryTemplateCustomizer = retryTemplateCustomizer;
	this.retryTemplate = new RetryTemplate();
}
 
Example 25
Source Project: distributed-lock   Source File: DefaultRetryTemplateConverter.java    License: MIT License 5 votes vote down vote up
@Override
public RetryTemplate construct(final Locked locked) {
  final var retryTemplate = new RetryTemplate();
  retryTemplate.setRetryPolicy(resolveLockRetryPolicy(locked));
  retryTemplate.setBackOffPolicy(resolveBackOffPolicy(locked));
  return retryTemplate;
}
 
Example 26
Source Project: distributed-lock   Source File: RetriableLockTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldNotRetryWhenFirstAttemptIsSuccessful() {
  when(lock.acquire(anyList(), anyString(), anyLong()))
    .thenReturn("abc");

  final var retryTemplate = new RetryTemplate();
  retryTemplate.setRetryPolicy(new NeverRetryPolicy());

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

  assertThat(token).isEqualTo("abc");
}
 
Example 27
Source Project: distributed-lock   Source File: RetriableLockTest.java    License: 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 28
/**
 * * @param clusterName name of the cluster
 *
 * @param inetAddresses addresses to connect to
 * @param preBuiltTransportClientFactory {@link PreBuiltTransportClientFactory} used to create the
 *     client
 * @param retryTemplate {@link RetryTemplate} to keep trying to connect
 * @param clusterName name of the cluster
 */
public ClientFactory(
    RetryTemplate retryTemplate,
    String clusterName,
    List<InetSocketAddress> inetAddresses,
    PreBuiltTransportClientFactory preBuiltTransportClientFactory) {
  this.retryTemplate = Objects.requireNonNull(retryTemplate);
  this.clusterName = Objects.requireNonNull(clusterName);
  this.inetAddresses = Objects.requireNonNull(inetAddresses);
  if (inetAddresses.isEmpty()) {
    throw new IllegalArgumentException("inetAddresses cannot be empty");
  }
  this.preBuiltTransportClientFactory = Objects.requireNonNull(preBuiltTransportClientFactory);
}
 
Example 29
Source Project: eventapis   Source File: EventApisFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Bean("operationsKafkaListenerContainerFactory")
    public ConcurrentKafkaListenerContainerFactory<String, Operation> operationsKafkaListenerContainerFactory(
            ConsumerFactory<String, Operation> consumerFactory) {
        ConcurrentKafkaListenerContainerFactory<String, Operation> factory
                = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory);
        RetryTemplate retryTemplate = new RetryTemplate();
        factory.setRetryTemplate(retryTemplate);

        factory.setConcurrency(eventApisConfiguration.getEventBus().getConsumer().getOperationSchedulerPoolSize());
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(eventApisConfiguration.getEventBus().getConsumer().getOperationSchedulerPoolSize());
        scheduler.setBeanName("OperationsFactory-Scheduler");
        scheduler.initialize();
        factory.getContainerProperties().setScheduler(scheduler);
        ThreadPoolTaskScheduler consumerScheduler = new ThreadPoolTaskScheduler();
        consumerScheduler.setPoolSize(eventApisConfiguration.getEventBus().getConsumer().getOperationSchedulerPoolSize());
        consumerScheduler.setBeanName("OperationsFactory-ConsumerScheduler");
        consumerScheduler.initialize();

        factory.getContainerProperties().setPollTimeout(3000L);
        factory.getContainerProperties().setAckOnError(false);
        factory.getContainerProperties().setConsumerTaskExecutor(consumerScheduler);
        factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.RECORD);
        /**
         * This is Fix for Spring Kafka versions which does not have ConsumerAwareErrorHandler handler till 2.0
         * When Listener faces with error, it retries snapshot operation
         * See https://github.com/kloiasoft/eventapis/issues/44
         */
        factory.getContainerProperties().setTransactionManager(new EmptyTransactionManager());
//        factory.getContainerProperties().setTransactionManager(platformTransactionManager);
        return factory;
    }
 
Example 30
private RetryTemplate getRetryTemplate(){
    TimeoutRetryPolicy retryPolicy = new TimeoutRetryPolicy();
    retryPolicy.setTimeout(retryTimeoutMs);
    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    backOffPolicy.setBackOffPeriod(retryBackoffMs);

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