Skip to content

Instantly share code, notes, and snippets.

@mzakyalvan
Created December 4, 2018 16:19
Show Gist options
  • Save mzakyalvan/00cebd1c22e5acc95082ae4628df915c to your computer and use it in GitHub Desktop.
Save mzakyalvan/00cebd1c22e5acc95082ae4628df915c to your computer and use it in GitHub Desktop.
Caching sample using reactor extra's ```reactor.cache.CacheMono```
package reactor.caching;
import org.junit.Test;
import reactor.cache.CacheMono;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Signal;
import reactor.test.StepVerifier;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import static org.mockito.Mockito.*;
public class SimpleObjectCachingTests {
@Test
public void testCachingMono() {
String cacheKey = "sample.key";
AtomicReference<Object> objectStore = new AtomicReference<>();
Consumer<Object> readerSpy = mock(Consumer.class);
doNothing().when(readerSpy).accept(any());
ObjectFactory objectFactory = mock(ObjectFactory.class);
when(objectFactory.create()).thenReturn(Mono.fromCallable(() -> new Object()));
Consumer<Object> factorySpy = mock(Consumer.class);
doNothing().when(factorySpy).accept(any());
Function<String, Mono<Signal<?>>> cacheReader = key -> Mono.justOrEmpty(objectStore.get())
.doOnNext(readerSpy)
.map(Signal::next);
Mono<Object> cacheMono = CacheMono.lookup(cacheReader, cacheKey)
.onCacheMissResume(() -> objectFactory.create().doOnNext(factorySpy))
.andWriteWith((key, signal) -> Mono.fromRunnable(() -> objectStore.set(signal.get())));
StepVerifier.create(cacheMono.repeat(3))
.expectSubscription()
.thenAwait()
.expectNextCount(4)
.expectComplete()
.verify();
verify(objectFactory, times(4)).create();
verify(factorySpy, times(1)).accept(any());
verify(readerSpy, times(3)).accept(any());
verifyNoMoreInteractions(objectFactory, factorySpy, readerSpy);
}
interface ObjectFactory {
Mono<Object> create();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment