Why is the nxxx parameter of set() in Jedis exclusive?
Asked Answered
G

2

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?

Greggs answered 13/10, 2014 at 11:47 Comment(0)
C
11

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

jedis.setex(key, expireAfter, value);
Clamshell answered 13/10, 2014 at 11:50 Comment(3)
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 - redis.io/commands/setArgumentative
So if it will be removed then this question is still unanswered. please explain ...Argumentative
@Argumentative as noted in the Redis SETEX docs > 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.Patsypatt
P
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
Piselli answered 23/8, 2022 at 4:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.