Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

caffeine cache with cache manager - caffeine/no-op #22

Open
wants to merge 1 commit into
base: release-4.6.0
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions src/main/java/com/uci/utils/BotService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.inversoft.rest.ClientResponse;
import com.uci.utils.bot.util.BotUtil;
Expand All @@ -21,10 +20,13 @@
import org.checkerframework.checker.nullness.qual.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriBuilder;
import org.springframework.cache.Cache;

import reactor.core.publisher.Mono;
import reactor.core.publisher.Signal;
Expand Down Expand Up @@ -53,7 +55,7 @@ public class BotService {

public WebClient webClient;
public FusionAuthClient fusionAuthClient;
private Cache<Object, Object> cache;
private CacheManager cacheManager;

// public BotService(WebClient webClient, FusionAuthClient fusionAuthClient, Caffeine<Object, Object> caffeineCacheBuilder) {
// this.webClient = webClient;
Expand All @@ -79,7 +81,9 @@ public class BotService {
*/
public Mono<String> getCampaignFromStartingMessage(String startingMessage) {
String cacheKey = "bot-name-for-starting-message:" + startingMessage;
return CacheMono.lookup(key -> Mono.justOrEmpty(cache.getIfPresent(cacheKey) != null ? cache.getIfPresent(key).toString() : null)
Cache cache = cacheManager.getCache(cacheKey);

return CacheMono.lookup(key -> Mono.justOrEmpty(cache != null && cache.get(cacheKey) != null ? cache.get(cacheKey).get().toString() : null)
.map(Signal::next), cacheKey)
.onCacheMissResume(() -> webClient.get()
.uri(builder -> builder.path("admin/v1/bot/getByParam/").queryParam("startingMessage", startingMessage).build())
Expand Down Expand Up @@ -112,7 +116,9 @@ public Mono<String> getCampaignFromStartingMessage(String startingMessage) {

public Mono<String> getCurrentAdapter(String botName) {
String cacheKey = "adpater-of-bot: " + botName;
return CacheMono.lookup(key -> Mono.justOrEmpty(cache.getIfPresent(cacheKey) != null ? cache.getIfPresent(key).toString() : null)
Cache cache = cacheManager.getCache(cacheKey);

return CacheMono.lookup(key -> Mono.justOrEmpty(cache != null && cache.get(cacheKey) != null ? cache.get(cacheKey).get().toString() : null)
.map(Signal::next), cacheKey)
.onCacheMissResume(() -> webClient.get()
.uri(builder -> builder.path("admin/v1/bot/getByParam/").queryParam("name", botName).build()).retrieve()
Expand Down Expand Up @@ -147,7 +153,9 @@ public Mono<String> getCurrentAdapter(String botName) {

public Mono<String> getBotIDFromBotName(String botName) {
String cacheKey = "Bot-id-for-bot-name: " + botName;
return CacheMono.lookup(key -> Mono.justOrEmpty(cache.getIfPresent(cacheKey) != null ? cache.getIfPresent(key).toString() : null)
Cache cache = cacheManager.getCache(cacheKey);

return CacheMono.lookup(key -> Mono.justOrEmpty(cache != null && cache.get(cacheKey) != null ? cache.get(cacheKey).get().toString() : null)
.map(Signal::next), cacheKey)
.onCacheMissResume(() -> webClient.get().uri(new Function<UriBuilder, URI>() {
@Override
Expand Down Expand Up @@ -195,7 +203,9 @@ public String apply(String response) {
*/
public Mono<Map<String, String>> getGupshupAdpaterCredentials(String adapterID) {
String cacheKey = "gupshup-credentials-for-adapter: " + adapterID;
return CacheMono.lookup(key -> Mono.justOrEmpty((Map<String, String>) cache.getIfPresent(cacheKey))
Cache cache = cacheManager.getCache(cacheKey);

return CacheMono.lookup(key -> Mono.justOrEmpty(cache != null && cache.get(cacheKey) != null ? (Map<String, String>) cache.get(cacheKey).get() : null)
.map(Signal::next), cacheKey)
.onCacheMissResume(() -> webClient.get().uri(builder -> builder.path("admin/v1/adapter/getCredentials/" + adapterID).build())
.retrieve().bodyToMono(String.class).map(response -> {
Expand Down
21 changes: 15 additions & 6 deletions src/main/java/com/uci/utils/CampaignService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.inversoft.rest.ClientResponse;
import com.uci.utils.bot.util.BotUtil;
Expand All @@ -15,6 +14,8 @@
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.Cache;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

Expand All @@ -36,7 +37,7 @@ public class CampaignService {

public WebClient webClient;
public FusionAuthClient fusionAuthClient;
private Cache<Object, Object> cache;
private CacheManager cacheManager;

// private static final Cache<Object, Object> cache = Caffeine.newBuilder().maximumSize(1000)
// .expireAfterWrite(Duration.ofSeconds(300))
Expand All @@ -50,7 +51,9 @@ public class CampaignService {
*/
public Mono<JsonNode> getCampaignFromID(String campaignID) {
String cacheKey = "campaign-node-by-id:" + campaignID;
return CacheMono.lookup(key -> Mono.justOrEmpty((JsonNode) cache.getIfPresent(cacheKey))
Cache cache = cacheManager.getCache(cacheKey);

return CacheMono.lookup(key -> Mono.justOrEmpty(cache != null && cache.get(cacheKey) != null ? (JsonNode)cache.get(cacheKey).get() : null)
.map(Signal::next), cacheKey)
.onCacheMissResume(() -> webClient.get()
.uri(builder -> builder.path("admin/v1/bot/get/" + campaignID).build())
Expand Down Expand Up @@ -116,7 +119,9 @@ public Application getCampaignFromName(String campaignName) throws Exception {
*/
public Mono<JsonNode> getCampaignFromNameTransformer(String campaignName) {
String cacheKey = "campaign-node-by-name:" + campaignName;
return CacheMono.lookup(key -> Mono.justOrEmpty((JsonNode) cache.getIfPresent(cacheKey))
Cache cache = cacheManager.getCache(cacheKey);

return CacheMono.lookup(key -> Mono.justOrEmpty(cache != null && cache.get(cacheKey) != null ? (JsonNode)cache.get(cacheKey).get() : null)
.map(Signal::next), cacheKey)
.onCacheMissResume(() -> webClient.get()
.uri(builder -> builder.path("admin/v1/bot/search/").queryParam("name", campaignName).queryParam("match", true).build())
Expand Down Expand Up @@ -161,7 +166,9 @@ public JsonNode apply(String response) {
*/
public Mono<String> getFirstFormByBotID(String botID) {
String cacheKey = "form-by-bot-name:" + botID;
return CacheMono.lookup(key -> Mono.justOrEmpty(cache.getIfPresent(cacheKey) != null ? cache.getIfPresent(cacheKey).toString() : null)
Cache cache = cacheManager.getCache(cacheKey);

return CacheMono.lookup(key -> Mono.justOrEmpty(cache != null && cache.get(cacheKey) != null ? cache.get(cacheKey).get().toString() : null)
.map(Signal::next), cacheKey)
.onCacheMissResume(() -> webClient.get()
.uri(builder -> builder.path("admin/v1/bot/get/" + botID).build())
Expand Down Expand Up @@ -197,7 +204,9 @@ public String apply(String response) {

public Mono<String> getBotNameByBotID(String botID) {
String cacheKey = "bot-name-by-id:" + botID;
return CacheMono.lookup(key -> Mono.justOrEmpty(cache.getIfPresent(cacheKey) != null ? cache.getIfPresent(cacheKey).toString() : null)
Cache cache = cacheManager.getCache(cacheKey);

return CacheMono.lookup(key -> Mono.justOrEmpty(cache != null && cache.get(cacheKey) != null ? cache.get(cacheKey).get().toString() : null)
.map(Signal::next), cacheKey)
.onCacheMissResume(() -> webClient.get()
.uri(builder -> builder.path("admin/v1/bot/get/" + botID).build())
Expand Down
28 changes: 24 additions & 4 deletions src/main/java/com/uci/utils/UtilAppConfiguration.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,22 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.cache.support.NoOpCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.reactive.function.client.WebClient;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
@EnableCaching
@EnableAutoConfiguration
public class UtilAppConfiguration {

Expand All @@ -29,17 +36,30 @@ public class UtilAppConfiguration {
@Value("${caffeine.cache.exprie.duration.seconds}")
public Integer cacheExpireDuration;

@Bean
public Caffeine<Object, Object> caffeineCacheBuilder() {
return Caffeine.newBuilder()
.maximumSize(cacheMaxSize)
.expireAfterWrite(Duration.ofSeconds(cacheExpireDuration))
.recordStats();
}

@Bean
public Cache<Object, Object> cache() {
return caffeineCacheBuilder().build();
}
@Profile("!dev")
public CacheManager getRealCacheManager(Caffeine caffeine) {
log.info("Real cache enabled");
CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
caffeineCacheManager.setCaffeine(caffeine);
return caffeineCacheManager;
}

@Bean
@Profile("dev")
public CacheManager getNoOpCacheManager() {
log.info("No-op cache enabled");
NoOpCacheManager caffeineCacheManager = new NoOpCacheManager();
return caffeineCacheManager;
}

@Bean
public WebClient getWebClient() {
Expand Down
31 changes: 18 additions & 13 deletions src/main/java/com/uci/utils/cache/controller/CacheController.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.benmanes.caffeine.cache.Cache;

Expand All @@ -24,7 +25,7 @@
@RequestMapping(value = "/cache")
public class CacheController {
@Autowired
private Cache<Object, Object> cache;
private CacheManager cacheManager;

/**
* call this to invalidate all cache instances
Expand All @@ -36,10 +37,12 @@ public ResponseEntity getAll() {
try {
jsonNode = mapper.readTree("{\"id\":\"api.content.cache\",\"ver\":\"3.0\",\"ts\":\"2021-06-26T22:47:05Z+05:30\",\"responseCode\":\"OK\",\"result\":{}}");
JsonNode resultNode = mapper.createObjectNode();
cache.asMap().keySet().forEach(key -> {
String cacheName = key.toString();
((ObjectNode) resultNode).put(cacheName, cache.getIfPresent(cacheName).toString());
});
Collection<String> cacheNames = cacheManager.getCacheNames();
for (String name : cacheNames) {
((ObjectNode) resultNode).put(name, (cacheManager.getCache(name) != null
&& cacheManager.getCache(name).get(name) != null
? cacheManager.getCache(name).get(name).get().toString() : null));
}
((ObjectNode) jsonNode).put("result", resultNode);
return ResponseEntity.ok(jsonNode);
} catch (JsonMappingException e) {
Expand All @@ -57,14 +60,16 @@ public ResponseEntity getAll() {
*/
@DeleteMapping(path = "/removeAll")
public void removeAll() {
cache.asMap().keySet().forEach(key -> {
removeCache(key.toString());
});
}

private void removeCache(final String cacheName) {
if (cache.getIfPresent(cacheName) != null) {
cache.invalidate(cacheName);
Collection<String> cacheNames = cacheManager.getCacheNames();
for (String name : cacheNames) {
cacheManager.getCache(name).clear();
// removeCache(key.toString());
}
}

// private void removeCache(final String cacheName) {
// if (cache.getIfPresent(cacheName) != null) {
// cache.invalidate(cacheName);
// }
// }
}