org.springframework.retry.RetryContext Java Examples
The following examples show how to use
org.springframework.retry.RetryContext.
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 |
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: RdbmsRetryOperationsInterceptorTest.java From spring-cloud-aws with Apache License 2.0 | 7 votes |
@Test void testRetryContextIsAvailable() throws Throwable { RetryContext retryContext = mock(RetryContext.class); RetrySynchronizationManager.register(retryContext); MethodInvocation methodInvocation = mock(MethodInvocation.class); try { RdbmsRetryOperationsInterceptor interceptor = new RdbmsRetryOperationsInterceptor(); interceptor.invoke(methodInvocation); } finally { RetrySynchronizationManager.clear(); } verify(methodInvocation, times(1)).proceed(); }
Example #3
Source File: ApiExceptionRetryPolicyTest.java From cloudbreak with Apache License 2.0 | 6 votes |
@Test public void testWithExceptionDefaultAlwaysRetry() { ApiExceptionRetryPolicy policy = new ApiExceptionRetryPolicy(); RetryContext context = policy.open(null); ApiException apiException = mock(ApiException.class); when(apiException.getCode()).thenReturn(401); // ...so we can't retry this one... policy.registerThrowable(context, apiException); assertFalse(policy.canRetry(context)); // ...and we can retry this one... when(apiException.getCode()).thenReturn(502); policy.registerThrowable(context, apiException); assertTrue(policy.canRetry(context)); }
Example #4
Source File: ClientFactory.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
private Client tryCreateClient(RetryContext retryContext) throws InterruptedException { if (Thread.interrupted()) { throw new InterruptedException(); } TransportClient result = preBuiltTransportClientFactory .build(clusterName, null) .addTransportAddresses(createInetTransportAddresses()); if (result.connectedNodes().isEmpty()) { result.close(); LOG.error( "Failed to connect to Elasticsearch cluster '{}' on {}. Retry count = {}", clusterName, inetAddresses, retryContext.getRetryCount()); throw new MolgenisDataException( String.format( "Failed to connect to Elasticsearch cluster '%s' on %s. Is Elasticsearch running?", clusterName, inetAddresses)); } return result; }
Example #5
Source File: RetryConfigTest.java From batchers with Apache License 2.0 | 6 votes |
@Test public void whenRetryCallbackFails_retryTimeIsExponential() throws TaxWebServiceNonFatalException { long start = System.currentTimeMillis(); when(retryCallback.doWithRetry(any(RetryContext.class))) .thenThrow(new TaxWebServiceNonFatalException(new EmployeeTestBuilder().build(), Money.of(CurrencyUnit.EUR, 10), null, null, "boe")) .thenThrow(new TaxWebServiceNonFatalException(new EmployeeTestBuilder().build(), Money.of(CurrencyUnit.EUR, 10), null, null, "boe")) .thenReturn(any()); retryTemplate.execute(retryCallback); verify(retryCallback, times(3)).doWithRetry(any(RetryContext.class)); long end = System.currentTimeMillis(); long duration = end - start; assertThat(duration).isGreaterThanOrEqualTo(300); }
Example #6
Source File: DatabaseInstanceStatusRetryPolicyTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@Test void canRetry_retryPossibleDueToAvailableDatabase_returnsTrue() throws Exception { // Arrange AmazonRDS amazonRDS = mock(AmazonRDS.class); DatabaseInstanceStatusRetryPolicy policy = new DatabaseInstanceStatusRetryPolicy( amazonRDS, "test"); when(amazonRDS.describeDBInstances( new DescribeDBInstancesRequest().withDBInstanceIdentifier("test"))) .thenReturn(new DescribeDBInstancesResult().withDBInstances( new DBInstance().withDBInstanceStatus("available"))); RetryContext retryContext = policy.open(new RetryContextSupport(null)); // Act policy.registerThrowable(retryContext, new TransientDataAccessResourceException("not available")); // Assert assertThat(policy.canRetry(retryContext)).isTrue(); policy.close(retryContext); }
Example #7
Source File: DatabaseInstanceStatusRetryPolicyTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@Test void canRetry_retryNotPossibleDueToNoDatabase_returnsFalse() throws Exception { // Arrange AmazonRDS amazonRDS = mock(AmazonRDS.class); DatabaseInstanceStatusRetryPolicy policy = new DatabaseInstanceStatusRetryPolicy( amazonRDS, "test"); when(amazonRDS.describeDBInstances( new DescribeDBInstancesRequest().withDBInstanceIdentifier("test"))) .thenThrow(new DBInstanceNotFoundException("test")); RetryContext retryContext = policy.open(new RetryContextSupport(null)); // Act policy.registerThrowable(retryContext, new TransientDataAccessResourceException("not available")); // Assert assertThat(policy.canRetry(retryContext)).isFalse(); policy.close(retryContext); }
Example #8
Source File: JerseyClientRetryPolicy.java From cloudbreak with Apache License 2.0 | 6 votes |
@Override public boolean canRetry(RetryContext context) { Throwable lastThrowable = context.getLastThrowable(); if (lastThrowable == null) { return true; } else { LOGGER.debug(String.format("Retry attempt %s. %s", context.getRetryCount(), context.getLastThrowable())); if (lastThrowable instanceof WebApplicationException) { WebApplicationException wae = (WebApplicationException) lastThrowable; Response.StatusType statusInfo = wae.getResponse().getStatusInfo(); if (statusInfo.getFamily() == Response.Status.Family.CLIENT_ERROR) { return false; } else if (statusInfo.getStatusCode() == Response.Status.BAD_REQUEST.getStatusCode()) { return false; } } } return context.getRetryCount() <= RETRY_LIMIT; }
Example #9
Source File: LoadBalancedRecoveryCallback.java From spring-cloud-commons with Apache License 2.0 | 6 votes |
@Override public T recover(RetryContext context) throws Exception { Throwable lastThrowable = context.getLastThrowable(); if (lastThrowable != null) { if (lastThrowable instanceof RetryableStatusCodeException) { RetryableStatusCodeException ex = (RetryableStatusCodeException) lastThrowable; return createResponse((R) ex.getResponse(), ex.getUri()); } else if (lastThrowable instanceof Exception) { throw (Exception) lastThrowable; } } throw new RetryException("Could not recover", lastThrowable); }
Example #10
Source File: RetryLoadBalancerInterceptorTest.java From spring-cloud-commons with Apache License 2.0 | 6 votes |
@Test(expected = TerminatedRetryException.class) public void retryListenerTestNoRetry() throws Throwable { HttpRequest request = mock(HttpRequest.class); when(request.getURI()).thenReturn(new URI("http://noRetry")); LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); MyBackOffPolicy backOffPolicy = new MyBackOffPolicy(); this.lbProperties.setEnabled(true); RetryListener myRetryListener = new RetryListenerSupport() { @Override public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) { return false; } }; RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor( this.client, this.lbProperties, this.lbRequestFactory, new MyLoadBalancedRetryFactory(policy, backOffPolicy, new RetryListener[] { myRetryListener })); ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); interceptor.intercept(request, new byte[] {}, execution); }
Example #11
Source File: DatabaseInstanceStatusRetryPolicyTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@Test void canRetry_noExceptionRegistered_returnsTrue() throws Exception { // Arrange AmazonRDS amazonRDS = mock(AmazonRDS.class); DatabaseInstanceStatusRetryPolicy policy = new DatabaseInstanceStatusRetryPolicy( amazonRDS, "test"); RetryContext retryContext = new RetryContextSupport(null); // Act policy.open(retryContext); // Assert assertThat(policy.canRetry(retryContext)).isTrue(); }
Example #12
Source File: ApiExceptionRetryPolicy.java From cloudbreak with Apache License 2.0 | 6 votes |
@Override public boolean canRetry(RetryContext context) { Throwable lastThrowable = context.getLastThrowable(); if (lastThrowable == null) { return true; } if (lastThrowable instanceof ApiException) { if (context.getRetryCount() <= maxAttempts) { int code = ((ApiException) lastThrowable).getCode(); if (code != 0) { HttpStatus httpStatus = HttpStatus.valueOf(code); boolean httpStatus5xxServerError = httpStatus.is5xxServerError(); LOGGER.warn("{} Exception occurred during CM API call, retryable: {} ({}/{})", code, httpStatus5xxServerError, context.getRetryCount(), maxAttempts); return httpStatus5xxServerError; } } else { return false; } } return false; }
Example #13
Source File: AssetMappingService.java From mojito with Apache License 2.0 | 5 votes |
/** * Creates {@link TMTextUnit} for {@link AssetTextUnit}s that don't have a * MD5 matches. * * @param assetExtractionId a valid {@link AssetExtraction#id} * @param tmId a valid {@link TM#id} * @param assetId a valid {@link Asset#id} * @return the newly created {@link TMTextUnit}s */ protected List<TMTextUnit> createTMTextUnitForUnmappedAssetTextUnitsWithRetry(final Long assetExtractionId, final Long tmId, final Long assetId, User createdByUser) { return retryTemplate.execute(new RetryCallback<List<TMTextUnit>, DataIntegrityViolationException>() { @Override public List<TMTextUnit> doWithRetry(RetryContext context) throws DataIntegrityViolationException { if (context.getRetryCount() > 0) { long mapExactMatches = mapExactMatches(assetExtractionId, tmId, assetId); logger.error("Assume concurrent modification happened, perform remapping: {}", mapExactMatches); } return createTMTextUnitForUnmappedAssetTextUnits(createdByUser, assetExtractionId, tmId, assetId); } }); }
Example #14
Source File: ApiExceptionRetryPolicyTest.java From cloudbreak with Apache License 2.0 | 5 votes |
@Test public void testRetryLimitSubsequentState() { ApiException apiException = mock(ApiException.class); when(apiException.getCode()).thenReturn(500); ApiExceptionRetryPolicy policy = new ApiExceptionRetryPolicy(2); RetryContext context = policy.open(null); assertTrue(policy.canRetry(context)); policy.registerThrowable(context, apiException); assertTrue(policy.canRetry(context)); policy.registerThrowable(context, apiException); policy.registerThrowable(context, apiException); assertFalse(policy.canRetry(context)); }
Example #15
Source File: DatabaseInstanceStatusRetryPolicyTest.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@Test void canRetry_withResourceIdResolver_returnsTrue() throws Exception { // Arrange AmazonRDS amazonRDS = mock(AmazonRDS.class); ResourceIdResolver resourceIdResolver = mock(ResourceIdResolver.class); DatabaseInstanceStatusRetryPolicy policy = new DatabaseInstanceStatusRetryPolicy( amazonRDS, "foo"); when(amazonRDS.describeDBInstances( new DescribeDBInstancesRequest().withDBInstanceIdentifier("test"))) .thenReturn(new DescribeDBInstancesResult().withDBInstances( new DBInstance().withDBInstanceStatus("available"))); when(resourceIdResolver.resolveToPhysicalResourceId("foo")).thenReturn("test"); policy.setResourceIdResolver(resourceIdResolver); RetryContext retryContext = policy.open(new RetryContextSupport(null)); // Act policy.registerThrowable(retryContext, new TransientDataAccessResourceException("not available")); // Assert assertThat(policy.canRetry(retryContext)).isTrue(); policy.close(retryContext); }
Example #16
Source File: MetadataSyncPostProcessorTest.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testShouldSendSuccessEmailIfSyncSummaryIsError() { metadataSyncSummary.setImportReport( new ImportReport() ); metadataSyncSummary.getImportReport().setStatus( Status.ERROR ); metadataSyncSummary.setMetadataVersion( dataVersion ); MetadataRetryContext mockMetadataRetryContext = mock( MetadataRetryContext.class ); RetryContext mockRetryContext = mock( RetryContext.class ); when( mockMetadataRetryContext.getRetryContext() ).thenReturn( mockRetryContext ); boolean status = metadataSyncPostProcessor.handleSyncNotificationsAndAbortStatus( metadataSyncSummary, mockMetadataRetryContext, dataVersion ); assertTrue( status ); }
Example #17
Source File: MetadataRetryContextTest.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testShouldSetRetryContextCorrectly() throws Exception { RetryContext newMock = mock( RetryContext.class ); metadataRetryContext.setRetryContext( newMock ); assertEquals( newMock, metadataRetryContext.getRetryContext() ); }
Example #18
Source File: ApiExceptionRetryPolicyTest.java From cloudbreak with Apache License 2.0 | 5 votes |
@Test public void testRetryCount() { ApiException apiException = mock(ApiException.class); when(apiException.getCode()).thenReturn(401); when(apiException.getMessage()).thenReturn("foo"); ApiExceptionRetryPolicy policy = new ApiExceptionRetryPolicy(); RetryContext context = policy.open(null); assertNotNull(context); policy.registerThrowable(context, null); assertEquals(0, context.getRetryCount()); policy.registerThrowable(context, apiException); assertEquals(1, context.getRetryCount()); assertEquals("foo", context.getLastThrowable().getMessage()); }
Example #19
Source File: InterceptorRetryPolicy.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
@Override public boolean canRetry(RetryContext context) { LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext) context; if (lbContext.getRetryCount() == 0 && lbContext.getServiceInstance() == null) { // We haven't even tried to make the request yet so return true so we do lbContext.setServiceInstance( this.serviceInstanceChooser.choose(this.serviceName)); return true; } return this.policy.canRetryNextServer(lbContext); }
Example #20
Source File: ApiExceptionRetryPolicy.java From cloudbreak with Apache License 2.0 | 5 votes |
@Override public void registerThrowable(RetryContext context, Throwable throwable) { RetryContextSupport contextSupport = RetryContextSupport.class.cast(context); contextSupport.registerThrowable(throwable); if (throwable != null) { LOGGER.warn("Exception occurred during CM API call.", throwable); } }
Example #21
Source File: InterceptorRetryPolicy.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
@Override public void registerThrowable(RetryContext context, Throwable throwable) { LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext) context; // this is important as it registers the last exception in the context and also // increases the retry count lbContext.registerThrowable(throwable); // let the policy know about the exception as well this.policy.registerThrowable(lbContext, throwable); }
Example #22
Source File: DatabaseInstanceStatusRetryPolicy.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@Override public RetryContext open(RetryContext parent) { RetryContextSupport context = new RetryContextSupport(parent); context.setAttribute(DB_INSTANCE_ATTRIBUTE_NAME, getDbInstanceIdentifier()); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Starting RetryContext for database instance with identifier {}", getDbInstanceIdentifier()); } return context; }
Example #23
Source File: DatabaseInstanceStatusRetryPolicyTest.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@Test void canRetry_multipleDatabasesFoundForInstanceIdentifier_reportsException() throws Exception { // Arrange AmazonRDS amazonRDS = mock(AmazonRDS.class); DatabaseInstanceStatusRetryPolicy policy = new DatabaseInstanceStatusRetryPolicy( amazonRDS, "test"); DescribeDBInstancesResult describeDBInstancesResult = new DescribeDBInstancesResult() .withDBInstances(new DBInstance(), new DBInstance()); when(amazonRDS.describeDBInstances( new DescribeDBInstancesRequest().withDBInstanceIdentifier("test"))) .thenReturn(describeDBInstancesResult); RetryContext retryContext = policy.open(new RetryContextSupport(null)); // Act policy.registerThrowable(retryContext, new TransientDataAccessResourceException("not available")); // Assert assertThatThrownBy(() -> policy.canRetry(retryContext)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Multiple databases found for same identifier"); }
Example #24
Source File: DatabaseInstanceStatusRetryPolicy.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@Override public void close(RetryContext context) { context.removeAttribute(DB_INSTANCE_ATTRIBUTE_NAME); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Closing RetryContext for database instance with identifier {}", getDbInstanceIdentifier()); } }
Example #25
Source File: RetryLoadBalancerInterceptorTest.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
@Override public BackOffContext start(RetryContext retryContext) { return new BackOffContext() { @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }; }
Example #26
Source File: DatabaseInstanceStatusRetryPolicy.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@Override public void registerThrowable(RetryContext context, Throwable throwable) { ((RetryContextSupport) context).registerThrowable(throwable); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Registered Throwable of Type {} for RetryContext", throwable.getClass().getName()); } }
Example #27
Source File: DatabaseInstanceStatusRetryPolicy.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
private boolean isDatabaseAvailable(RetryContext context) { DescribeDBInstancesResult describeDBInstancesResult; try { describeDBInstancesResult = this.amazonRDS.describeDBInstances( new DescribeDBInstancesRequest().withDBInstanceIdentifier( (String) context.getAttribute(DB_INSTANCE_ATTRIBUTE_NAME))); } catch (DBInstanceNotFoundException e) { LOGGER.warn( "Database Instance with name {} has been removed or is not configured correctly, no retry possible", getDbInstanceIdentifier()); // Database has been deleted while operating, hence we can not retry return false; } if (describeDBInstancesResult.getDBInstances().size() == 1) { DBInstance dbInstance = describeDBInstancesResult.getDBInstances().get(0); InstanceStatus instanceStatus = InstanceStatus .fromDatabaseStatus(dbInstance.getDBInstanceStatus()); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Status of database to be retried is {}", instanceStatus); } return instanceStatus.isRetryable(); } else { throw new IllegalStateException( "Multiple databases found for same identifier, this is likely an incompatibility with the Amazon SDK"); } }
Example #28
Source File: InterceptorRetryPolicyTest.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
@Test public void open() throws Exception { InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy( this.request, this.policy, this.serviceInstanceChooser, this.serviceName); RetryContext context = interceptorRetryPolicy.open(null); then(context).isInstanceOf(LoadBalancedRetryContext.class); }
Example #29
Source File: CallWebserviceProcessor.java From batchers with Apache License 2.0 | 5 votes |
private RetryCallback<Void, TaxWebServiceException> doWebserviceCallWithRetryCallback(TaxCalculation taxCalculation) { return new RetryCallback<Void, TaxWebServiceException>() { @Override public Void doWithRetry(RetryContext context) throws TaxWebServiceException { taxPaymentWebService.doWebserviceCallToTaxService(taxCalculation.getEmployee(), taxCalculation.getTax()); return null; } }; }
Example #30
Source File: AssetExtractionService.java From mojito with Apache License 2.0 | 5 votes |
/** * Marks the provided asset extraction as current extraction for the branch. * <p> * Make the function {@link Retryable} since this can have concurrent access issue when multiple thread trying to save * the active asset extraction at the same time. It is not important which one wins last since in real usage * that should not really happen, it is an edge case and the code just need to be safe. * * @param assetExtraction */ private void markAssetExtractionForBranch(final AssetExtraction assetExtraction) { final Asset asset = assetExtraction.getAsset(); final Branch branch = assetExtraction.getAssetContent().getBranch(); logger.debug("markAssetExtractionForBranch, assetId: {}, branch: {}", asset.getId(), branch.getName()); retryTemplate.execute(new RetryCallback<AssetExtractionByBranch, DataIntegrityViolationException>() { @Override public AssetExtractionByBranch doWithRetry(RetryContext context) throws DataIntegrityViolationException { if (context.getRetryCount() > 0) { logger.debug("Concurrent modification happened when saving the active asset extraction, retry"); } AssetExtractionByBranch assetExtractionByBranch = assetExtractionByBranchRepository.findByAssetAndBranch(assetExtraction.getAsset(), branch); if (assetExtractionByBranch == null) { assetExtractionByBranch = new AssetExtractionByBranch(); assetExtractionByBranch.setAsset(assetExtraction.getAsset()); assetExtractionByBranch.setBranch(branch); } assetExtractionByBranch.setAssetExtraction(assetExtraction); assetExtractionByBranch.setDeleted(false); assetExtractionByBranch = assetExtractionByBranchRepository.save(assetExtractionByBranch); return assetExtractionByBranch; } }); }