|
| 1 | +[Failsafe's][failsafe] retry, timeout, and fallback strategies can be used to make the cache |
| 2 | +operations resiliant to intermittent failures. |
| 3 | + |
| 4 | +### Retry |
| 5 | +A [retry policy][retry] will retry failed executions a certain number of times, with an optional |
| 6 | +delay between attempts. |
| 7 | + |
| 8 | +```java |
| 9 | +var retryPolicy = RetryPolicy.builder() |
| 10 | + .withDelay(Duration.ofSeconds(1)) |
| 11 | + .withMaxAttempts(3) |
| 12 | + .build(); |
| 13 | +var failsafe = Failsafe.with(retryPolicy); |
| 14 | + |
| 15 | +// Retry outside of the cache loader for synchronous calls |
| 16 | +Cache<K, V> cache = Caffeine.newBuilder().build(); |
| 17 | +failsafe.get(() -> cache.get(key, key -> /* intermittent failures */ )); |
| 18 | + |
| 19 | +// Optionally, retry inside the cache load for asynchronous calls |
| 20 | +AsyncCache<K, V> asyncCache = Caffeine.newBuilder().buildAsync(); |
| 21 | +asyncCache.get(key, (key, executor) -> failsafe.getAsync(() -> /* intermittent failure */)); |
| 22 | +``` |
| 23 | + |
| 24 | +### Timeout |
| 25 | +A [timeout policy][timeout] will cancel the execution if it takes too long to complete. |
| 26 | + |
| 27 | +```java |
| 28 | +var retryPolicy = RetryPolicy.builder() |
| 29 | + .withDelay(Duration.ofSeconds(1)) |
| 30 | + .withMaxAttempts(3) |
| 31 | + .build(); |
| 32 | +var timeout = Timeout.builder(Duration.ofSeconds(1)).withInterrupt().build(); |
| 33 | +var failsafe = Failsafe.with(timeout, retryPolicy); |
| 34 | + |
| 35 | +Cache<K, V> cache = Caffeine.newBuilder().build(); |
| 36 | +failsafe.get(() -> cache.get(key, key -> /* timeout */ )); |
| 37 | +``` |
| 38 | + |
| 39 | +### Fallback |
| 40 | +A [fallback policy][fallback] will provide an alternative result for a failed execution. |
| 41 | + |
| 42 | +```java |
| 43 | +var retryPolicy = RetryPolicy.builder() |
| 44 | + .withDelay(Duration.ofSeconds(1)) |
| 45 | + .withMaxAttempts(3) |
| 46 | + .build(); |
| 47 | +var fallback = Fallback.of(/* fallback */); |
| 48 | +var failsafe = Failsafe.with(fallback, retryPolicy); |
| 49 | + |
| 50 | +Cache<K, V> cache = Caffeine.newBuilder().build(); |
| 51 | +failsafe.get(() -> cache.get(key, key -> /* failure */ )); |
| 52 | +``` |
| 53 | + |
| 54 | +[failsafe]: https://failsafe.dev |
| 55 | +[retry]: https://failsafe.dev/retry |
| 56 | +[timeout]: https://failsafe.dev/timeout |
| 57 | +[fallback]: https://failsafe.dev/fallback |
0 commit comments