Skip to content

Commit

Permalink
setting redis ttl while sync to redis instead of increment op
Browse files Browse the repository at this point in the history
  • Loading branch information
ag060 committed Jan 2, 2025
1 parent 14f676f commit abc1f37
Showing 1 changed file with 8 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import io.lettuce.core.ExpireArgs;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.*;

public class RedisBackedCounterCache implements CounterCache {
Expand Down Expand Up @@ -39,8 +41,7 @@ public long getValue() {
public RedisBackedCounterCache(RedisClient redisClient, String prefix) {
this.prefix = prefix;
this.redis = redisClient.connect(new LongValueCodec());
this.localCache =
Caffeine.newBuilder().maximumSize(100000).expireAfterWrite(3, TimeUnit.HOURS).build();
this.localCache = Caffeine.newBuilder().maximumSize(100000).expireAfterWrite(3, TimeUnit.HOURS).build();

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(this::syncToRedis, 60, 5, TimeUnit.SECONDS);
Expand All @@ -63,8 +64,6 @@ public void incrementBy(String key, long val) {
String _key = addPrefixToKey(key);
localCache.asMap().merge(_key, val, Long::sum);
pendingIncOps.add(new Op(_key, val));

this.setExpiryIfNotSet(_key, 3 * 60 * 60); // added 3 hours expiry for now
}

@Override
Expand Down Expand Up @@ -93,6 +92,7 @@ private void setExpiryIfNotSet(String key, long seconds) {
}

private void syncToRedis() {
Set<String> _keys = new HashSet<>();
while (!pendingIncOps.isEmpty()) {
Op op = pendingIncOps.poll();
String key = op.getKey();
Expand All @@ -111,12 +111,16 @@ private void syncToRedis() {
ex.printStackTrace();
}

_keys.add(key);

if (result != null) {
localCache.asMap().put(key, result);
}
});
}

_keys.forEach(key -> setExpiryIfNotSet(key, 3 * 60 * 60));

this.deletedKeys.clear();
}
}

0 comments on commit abc1f37

Please sign in to comment.