2

I have a function that use lettuce to talk to a redis cluster.

In this function, I insert data into a stream data structure.

import io.lettuce.core.cluster.SlotHash;

...

public void addData(Map<String, String> dataMap) {

var sync = SlotHash.getSlot(key).sync()

sync.xadd(key, dataMap);

}

I also want to set the ttl when I insert a record for the first time. It is because part of the user requirement is expire the structure after a fix length of time. In this case it is 10 hour.

Unfortunately the XADD function does not accept an extra parameter to set the TTL like the SET function.

So now I am setting the ttl this way:

public void addData(Map<String, String> dataMap) {

var sync = SlotHash.getSlot(key).sync()

sync.xadd(key, dataMap);
sync.expire(key, 60000 /* 10 hours */); 

}

What is the best way to ensure the I will set the expiry time only once (i.e. when the stream structure is first created)? I should not set TTL multiple times within the function because every call to xadd will also follow by a call of expire which effectively postpone the expiry time indefinitely.

I think I can always check the number of items in the stream data structure but it is an overhead. I don't want to keep flags in the java application side because the app could be restarted and this information will be removed from the memory.

Anthony Kong
  • 37,791
  • 46
  • 172
  • 304

1 Answers1

1

You may want to try lua script, sample script below which sets the expiry only if it's not set for key, works with any type of key in redis.

eval "local ttl = redis.call('ttl', KEYS[1]); if ttl == -1 then redis.call('expire', KEYS[1], ARGV[1]); end; return ttl;" 1 mykey 12

script also returns the actual expiry time left in seconds.

tabreaz
  • 649
  • 4
  • 17