7

In Jedis, I want to set some key and value with expiring time by a single invocation.

I can do this by combination of set() and expire() but it needs two invocations.

I found the following method:

set(final String key, final String value, final String nxxx, final String expx, final long time)

But I have to choose nx (Only set the key if it does not already exist.) or xx (Only set the key if it already exist.).

I want to cover both cases.

Any suggestion? Or any reason to be written like this?

Johnny Lim
  • 5,623
  • 8
  • 38
  • 53

2 Answers2

11

Redis has a SETEX command, which sets the key with an expiry.

jedis.setex(key, expireAfter, value);
c.P.u1
  • 16,664
  • 6
  • 46
  • 41
  • Note: Since the SET command options can replace SETNX, SETEX, PSETEX, it is possible that in future versions of Redis these three commands will be deprecated and finally removed. Source - https://redis.io/commands/set – LoveToCode Jun 12 '17 at 06:30
  • 1
    So if it will be removed then this question is still unanswered. please explain ... – LoveToCode Jun 12 '17 at 06:31
  • @LoveToCode as noted in the [Redis `SETEX` docs](https://redis.io/commands/setex) > `SET mykey value` > `EXPIRE mykey seconds` > SETEX is atomic, and can be reproduced by using the previous two commands inside an MULTI / EXEC block. Thus it could be the following Jedis: ```java final String key = "foo"; final Transaction t = jedis.multi(); t.set(key, "bar"); // Set the key with the value t.expire(key, 10); // Set it to expire in 10 seconds t.exec(); ``` But I'd image Jedis would make the change under the hood if `SETEX` is removed. – 3ygun Nov 23 '18 at 19:36
0

This question is so misleading. nx and xx are indeed for different use cases and mutually exclusive. If you want to simply overwrite any expiry, simply don't pass in none of below:

  • NX -- Set the key only when the key doesn't exist
  • XX -- Set the key only when the key has existed
Stan
  • 602
  • 6
  • 23