Skip to content

Instantly share code, notes, and snippets.

@stefanotroia
Last active December 11, 2019 07:52
Show Gist options
  • Save stefanotroia/bb37d0d9a82e39b11623cce63afe0ae1 to your computer and use it in GitHub Desktop.
Save stefanotroia/bb37d0d9a82e39b11623cce63afe0ae1 to your computer and use it in GitHub Desktop.
Book service with caching
@Service
@Slf4j
public class BookService extends BaseService<Book> {
private BookRepository repository;
@Autowired
public BookService(BookRepository repository) {
this.repository = repository;
}
@Override
public Mono<Book> findById(String bookId) {
log.info("Requesting BOOK with id {}", bookId);
List<String> cacheKeys = Collections.singletonList(bookId);
return findCacheValue("OUR_CACHE", cacheKeys, repository.findFirstByBookId(bookId));
}
public Mono<Book> save(Book book) {
return Mono.just(book)
.flatMap(b -> repository.save(b))
.doOnNext(b -> writeCacheValue("OUR_CACHE", Collections.singletonList(b.getId()),b));
}
@Override
public Mono<Book> update(String bookId, Book book) {
return findById(bookId)
.flatMap(b -> save(book));
}
@Override
public Mono<Void> delete(String bookId) {
return findById(bookId)
.doOnNext(b -> evictValue("OUR_CACHE", Collections.singletonList(b.getId())))
.flatMap(b -> {repository.delete(b); return Mono.empty();});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment