I have a question about caching in Spring Boot. I created my own cache service and cache manager. I will have to manually invalidate this cache and reload it when user performs some actions in frontend.
I would be now able to put elements to such cache. But I don't know two things:
- How can I put All elements from some collection to cache without iterating such collection, there is no putAll method on cache ?
- It possible to invalidate cache by using clear method which I implemented below, but what then? How this cache would reload - I have to load the cache manually by myself ? Couldn't it reload itself automatically imediatelly after I invalidate it ?
- If none of above is possible, in my scenario, whats the point of using cache if simple hashmap would do the same ..
Cache manager
@Configuration
@EnableCaching
public class MyCache {
@Bean
public CacheManager cacheManager() {
return new SimpleCacheManager();
}
}
Cache service
@Component
@RequiredArgsConstructor
public class CachingService {
private final CacheManager cacheManager;
public void putToCache(String cacheName, String key, String value) {
Optional.ofNullable(cacheManager.getCache(cacheName)).ifPresentOrElse(c -> c.put(key, value),
() -> {
throw new IllegalArgumentException("Cache with name %s does not exist");
});
}
public void putAllToCache(String cacheName, Map<String, String> keyValueMap) {
Optional.ofNullable(cacheManager.getCache(cacheName)).ifPresentOrElse(c -> c.put(key, value),
//TODO do I have to iterate all keyValueMap entries ?? there is no putAll ?
() -> {
throw new IllegalArgumentException("Cache with name %s does not exist");
});
}
public String getFromCache(String cacheName, String key) {
return Optional.ofNullable(cacheManager.getCache(cacheName)).map(c -> c.get(key)).map(Object::toString)
.orElse(null);
}
public void evictSingleCacheValue(String cacheName, String cacheKey) {
cacheManager.getCache(cacheName).evict(cacheKey);
}
public void evictAllCacheValues(String cacheName) {
cacheManager.getCache(cacheName).clear();
}
public void evictAllCaches() {
cacheManager.getCacheNames()
.parallelStream()
.forEach(cacheName -> cacheManager.getCache(cacheName).clear());
}
}