DECRBY
Decrement the value stored in key by the given decrement value.
If the key does not exist, the key’s value will first be initialized to 0, and then the DECRBY operation will be performed.
If the value contains the wrong type, or the string value cannot be represented as a number, an error is returned.
The value of this operation is limited to 64-bit signed number representation.
Redis Native Command Syntax
Section titled “Redis Native Command Syntax”DECRBY key decrementParameter Description
- key: The key to decrement
- decrement: The decrement value (can be negative, negative means increase)
Detailed Explanation
Section titled “Detailed Explanation”The DECRBY command is an atomic operation and can be used to implement counter functionality. It is an operation for string type, but requires the string to be parseable as an integer.
Compared to the DECR command, DECRBY allows specifying a specific decrement value, not limited to 1.
Redisun Usage
Section titled “Redisun Usage”In redisun, the DECRBY command is implemented through the DecrByCommand class and the decrBy method in the Redisun class.
Basic Usage
Section titled “Basic Usage”Redisun redisun = Redisun.create(options -> { options.setAddress("redis://127.0.0.1:6379");});
// Decrement the key's value (decrease by 10)long result = redisun.decrBy("mycounter", 10);System.out.println("Counter value: " + result);
// Asynchronous versionCompletableFuture<Long> future = redisun.asyncDecrBy("mycounter", 10);future.thenAccept(value -> System.out.println("Async counter value: " + value));Using Negative Numbers to Implement Increase Operations
Section titled “Using Negative Numbers to Implement Increase Operations”// Increase the key's value (decrease by -5, i.e., increase by 5)long result = redisun.decrBy("mycounter", -5);System.out.println("Counter value: " + result);- If the key does not exist, it will be automatically created and initialized to 0
- If the key exists but is not a numeric string, an exception will be thrown
- The value range is limited to 64-bit signed integer range
- The operation is atomic and suitable for concurrent scenarios
- The decrement parameter can be negative, in which case it implements an increase operation