Support Raw Keys

If the key generator is guaranteed to provide a unique key, it can be used as
the cache key directly.

Add a setter to support this option.
This commit is contained in:
Gary Russell
2016-10-12 12:47:34 -04:00
committed by Dave Syer
parent 507c62bdae
commit 3726eef3ba
2 changed files with 38 additions and 0 deletions

View File

@@ -71,6 +71,8 @@ public class StatefulRetryOperationsInterceptor implements MethodInterceptor {
private Classifier<? super Throwable, Boolean> rollbackClassifier;
private boolean useRawKey;
public StatefulRetryOperationsInterceptor() {
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(new NeverRetryPolicy());
@@ -123,6 +125,17 @@ public class StatefulRetryOperationsInterceptor implements MethodInterceptor {
this.newMethodArgumentsIdentifier = newMethodArgumentsIdentifier;
}
/**
* Set to true to use the raw key generated by the key generator. Should only be set
* to true for cases where the key is guaranteed to be unique in all cases. When
* false, a compound key is used, including invocation metadata.
* Default: false.
* @param useRawKey the useRawKey to set.
*/
public void setUseRawKey(boolean useRawKey) {
this.useRawKey = useRawKey;
}
/**
* Wrap the method invocation in a stateful retry with the policy and other helpers
* provided. If there is a failure the exception will generally be re-thrown. The only
@@ -181,6 +194,9 @@ public class StatefulRetryOperationsInterceptor implements MethodInterceptor {
// really doesn't want to retry.
return null;
}
if (this.useRawKey) {
return generatedKey;
}
String name = StringUtils.hasText(label) ? label
: invocation.getMethod().toGenericString();
return Arrays.asList(name, generatedKey);

View File

@@ -268,6 +268,28 @@ public class StatefulRetryOperationsInterceptorTests {
assertNull(captor.getValue().getKey());
}
@SuppressWarnings("unchecked")
@Test
public void testKeyGeneratorAndRawKey() throws Throwable {
this.interceptor.setKeyGenerator(new MethodArgumentsKeyGenerator() {
@Override
public Object getKey(Object[] item) {
return "bar";
}
});
this.interceptor.setLabel("foo");
this.interceptor.setUseRawKey(true);
RetryOperations template = mock(RetryOperations.class);
this.interceptor.setRetryOperations(template);
MethodInvocation invocation = mock(MethodInvocation.class);
when(invocation.getArguments()).thenReturn(new Object[] { new Object() });
this.interceptor.invoke(invocation);
ArgumentCaptor<DefaultRetryState> captor = ArgumentCaptor.forClass(DefaultRetryState.class);
verify(template).execute(any(RetryCallback.class), any(RecoveryCallback.class), captor.capture());
assertEquals("bar", captor.getValue().getKey());
}
@Test
public void testTransformerRecoveryAfterTooManyAttempts() throws Exception {
((Advised) transformer).addAdvice(interceptor);