Last active
July 18, 2022 13:16
-
-
Save rponte/634e60427309c5fc273bb6cf79d4fc8b to your computer and use it in GitHub Desktop.
Simple CacheStore using Guava Cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.cache.Cache; | |
import com.google.common.cache.CacheBuilder; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import javax.annotation.PostConstruct; | |
import java.util.Optional; | |
import java.util.concurrent.TimeUnit; | |
@Component | |
public class CacheStore { | |
private static final Logger LOGGER = LoggerFactory.getLogger(CacheStore.class); | |
private Cache<String, ExpensiveObject> cache; | |
@PostConstruct | |
public void initCache() { | |
/** | |
* Desafio aqui eh encontrar politica de cache no workload real para: | |
* 1. maximizar o cache-hit, ideal +90% | |
* 2. diminuir os ciclos de GC (minors e principalmente fulls) | |
* 3. permitir funcionamento normal da app e picos de acessos | |
*/ | |
this.cache = CacheBuilder.newBuilder() | |
.maximumSize(100_000) | |
.expireAfterWrite(1, TimeUnit.DAYS) | |
.build(); | |
} | |
public Optional<ExpensiveObject> get(String id) { | |
ExpensiveObject object = cache.getIfPresent(id); | |
return Optional.ofNullable(object); | |
} | |
public void update(String id, ExpensiveObject object) { | |
LOGGER.info("[CACHE] Putting key '{}' in cache", id); | |
cache.put(id, object); | |
} | |
public void remove(String id) { | |
LOGGER.info("[CACHE] Removing key '{}' from cache", id); | |
this.cache.invalidate(id); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<dependency> | |
<groupId>com.google.guava</groupId> | |
<artifactId>guava</artifactId> | |
<version>31.0.1-jre</version> | |
</dependency> |
Author
rponte
commented
Nov 19, 2021
- Cache using ConcurrentHashMap
- To implement Java local caching, start from these points
We can use this new lib, ExpiringMap: A high performance, low-overhead, zero dependency, thread-safe ConcurrentMap implementation that expires entries.
ExpiringMap allows you to create a map that expires entries after a certain time period or when a maximum map size has been exceeded:
Map<String, Connection> map = ExpiringMap.builder()
.maxSize(123)
.expiration(30, TimeUnit.SECONDS)
.build();
// Expires after 30 seconds or as soon as a 124th element is added and this is the next one to expire based on the expiration policy
map.put("connection", connection);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment