JAVA-16681 GitHub Issue: CacheUtils shown in this tutorial are now Deprecated and marked for removal (#13397)
Co-authored-by: timis1 <noreplay@yahoo.com>
This commit is contained in:
parent
edba3b292b
commit
5f1cc6ddba
@ -1,22 +1,22 @@
|
||||
package com.baeldung.webflux.caching;
|
||||
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import com.github.benmanes.caffeine.cache.LoadingCache;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.cache.CacheMono;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Service
|
||||
public class ItemService {
|
||||
|
||||
private final ItemRepository repository;
|
||||
private final LoadingCache<String, Object> cache;
|
||||
private final LoadingCache<String, Mono<Item>> cache;
|
||||
|
||||
public ItemService(ItemRepository repository) {
|
||||
this.repository = repository;
|
||||
this.cache = Caffeine.newBuilder()
|
||||
.build(this::getItem_withAddons);
|
||||
this.cache = Caffeine.newBuilder().build(this::getItem_withCaffeine);
|
||||
}
|
||||
|
||||
@Cacheable("items")
|
||||
@ -34,9 +34,7 @@ public class ItemService {
|
||||
}
|
||||
|
||||
@Cacheable("items")
|
||||
public Mono<Item> getItem_withAddons(String id) {
|
||||
return CacheMono.lookup(cache.asMap(), id)
|
||||
.onCacheMissResume(() -> repository.findById(id).cast(Object.class)).cast(Item.class);
|
||||
public Mono<Item> getItem_withCaffeine(String id) {
|
||||
return cache.asMap().computeIfAbsent(id, k -> repository.findById(id).cast(Item.class));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -73,19 +73,19 @@ public void givenItem_whenGetItemIsCalled_thenMonoIsCached() {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenItem_whenGetItemWithAddonsIsCalled_thenMonoResultIsCached() {
|
||||
public void givenItem_whenGetItemWithCaffeineIsCalled_thenMonoResultIsCached() {
|
||||
Mono<Item> glass = itemService.save(new Item("glass", 1.00));
|
||||
|
||||
String id = glass.block().get_id();
|
||||
|
||||
Mono<Item> mono = itemService.getItem_withAddons(id);
|
||||
Mono<Item> mono = itemService.getItem_withCaffeine(id);
|
||||
Item item = mono.block();
|
||||
|
||||
assertThat(item).isNotNull();
|
||||
assertThat(item.getName()).isEqualTo("glass");
|
||||
assertThat(item.getPrice()).isEqualTo(1.00);
|
||||
|
||||
Mono<Item> mono2 = itemService.getItem_withAddons(id);
|
||||
Mono<Item> mono2 = itemService.getItem_withCaffeine(id);
|
||||
Item item2 = mono2.block();
|
||||
|
||||
assertThat(item2).isNotNull();
|
||||
|
Loading…
x
Reference in New Issue
Block a user