HSETNX is a command in Redis which sets field in the hash stored at key to value, only if field does not yet exist. In essence, it's a "Set If Not Exists" operation on a hash. Common use cases of HSETNX in Java are:
Let's take two examples using the Jedis library to perform HSETNX operations.
import redis.clients.jedis.Jedis; public class Main { public static void main(String[] args) { Jedis jedis = new Jedis("localhost"); long result = jedis.hsetnx("user:1001", "name", "John Doe"); System.out.println("Result: " + result); jedis.close(); } }
In this example, we're setting a new field name
with the value John Doe
for the hash user:1001
if it doesn't already exist. The hsetnx
method returns 1 if the field was set and 0 if it wasn't (because it already exists).
import redis.clients.jedis.Jedis; public class Main { public static void main(String[] args) { Jedis jedis = new Jedis("localhost"); long lockStatus = jedis.hsetnx("lock", "resource1", "true"); if (lockStatus == 1) { try { // critical section } finally { jedis.hdel("lock", "resource1"); } } else { System.out.println("Resource is locked."); } jedis.close(); } }
In this example, different processes can attempt to set a lock on resource1
. If hsetnx
returns 1, the process has successfully acquired the lock and can proceed with its operations.
finally
block to prevent connection leaks.Q: Can HSETNX update an existing field value in Redis hash? A: No. HSETNX will not update an existing field. It will only set new fields if they do not exist in the hash.
Q: What kind of values does HSETNX return? A: The command HSETNX will return integer reply, specifically, 1 if field is a new field in the hash and value was set, 0 if field already exists in the hash and no operation was performed.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.