com.datorama.oss.timbermill.common.cache.RedisCacheHandler Maven / Gradle / Ivy
package com.datorama.oss.timbermill.common.cache;
import com.datorama.oss.timbermill.common.redis.RedisService;
import com.datorama.oss.timbermill.unit.LocalTask;
import com.github.jedis.lock.JedisLock;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class RedisCacheHandler extends AbstractCacheHandler {
private static final String LOCK_NAME = "cache_lock";
private static final String ORPHAN_PREFIX = "orphan###";
private static final Logger LOG = LoggerFactory.getLogger(RedisCacheHandler.class);
private JedisLock lock;
private final RedisService redisService;
private final int redisTtlInSeconds;
RedisCacheHandler(RedisService redisService, int cacheRedisTtlInSeconds) {
if (redisService == null){
throw new RuntimeException("Redis cache used but no redis host defined");
}
this.redisService = redisService;
this.redisTtlInSeconds = cacheRedisTtlInSeconds;
}
@Override
public Map> pullFromOrphansCache(Collection parentsIds) {
Set orphanParentsIds = parentsIds.stream().map(s -> ORPHAN_PREFIX + s).collect(Collectors.toSet());
Map> orphans = redisService.getFromRedis(orphanParentsIds);
Map> retMap = Maps.newHashMap();
for (Map.Entry> entry : orphans.entrySet()) {
String newKey = entry.getKey().substring(ORPHAN_PREFIX.length());
retMap.put(newKey, entry.getValue());
}
return retMap;
}
@Override
public void pushToOrphanCache(Map> orphansMap) {
Map> newOrphansMap = Maps.newHashMap();
for (Map.Entry> entry : orphansMap.entrySet()) {
String orphanCacheKey = ORPHAN_PREFIX + entry.getKey();
newOrphansMap.put(orphanCacheKey, entry.getValue());
}
if (!redisService.pushToRedis(newOrphansMap, redisTtlInSeconds)){
LOG.error("Failed to push some ids to Redis orphans cache.");
}
}
@Override
public Map getFromTasksCache(Collection idsList) {
return redisService.getFromRedis(idsList);
}
@Override
public void pushToTasksCache(Map idsToMap) {
boolean allPushed = redisService.pushToRedis(idsToMap, redisTtlInSeconds);
if (!allPushed){
LOG.error("Failed to push some ids to Redis tasks cache.");
}
}
@Override
public void lock() {
lock = redisService.lock(LOCK_NAME);
}
@Override
public void release() {
redisService.release(lock);
}
@Override
public void close() {
redisService.close();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy