Conteúdo do Curso
Introduction to Redis
Introduction to Redis
INCR and DECR Commands
These operations are atomic, meaning they are either fully completed or not executed at all, ensuring data consistency even when multiple processes access Redis simultaneously.
INCR Command
The INCR
command increases a numeric value by one. It is particularly useful for scenarios like counting page views or tracking the number of likes.
Let's simulate a situation where we track the number of views on a webpage:
If the key does not exist, Redis will create it and set its value to 1
. Each subsequent call to the command will increase the value by 1
, updating the counter to 2
, 3
, and so on.
If you need to increment the value of the same key multiple times, you can use the INCRBY
command and specify how much you want to increase the value.
In this example, the INCRBY
command increases the value of the page:main
key by 5. If the initial value was 0, it will become 5 after executing the command.
DECR Command
The DECR
command works similarly to INCR
, but it decreases the value by one. This is useful in scenarios like inventory tracking, where you need to reduce the stock count each time an item is sold.
Let's simulate tracking the number of available products in stock:
On the first call to the command, the value will decrease to -1
. Each subsequent call will decrease the value by 1
(to -2
, -3
, and so on).
If you need to decrement the value of the same key multiple times, you can use the DECRBY
command and specify how much you want to decrease the value.
In this example, the DECRBY
command decreases the value of the product:count
key by 3. If the initial value was 10, it will become 7 after executing the command.
1. What does the INCR
command do in Redis?
2. What happens if the key does not exist when you use INCR
or DECR
?
3. What happens if the key contains a non-numeric value and you use INCR
or DECR
?
Obrigado pelo seu feedback!