0
0
Redisquery~5 mins

Counter pattern in Redis

Choose your learning style9 modes available
Introduction

The counter pattern helps you count things easily, like visits or clicks, using Redis. It keeps track of numbers fast and simply.

Counting how many times a webpage is visited.
Tracking the number of likes on a post.
Keeping score in a game.
Counting how many times a product is bought.
Monitoring how many users are online.
Syntax
Redis
INCR key
INCRBY key increment
DECR key
DECRBY key decrement
GET key

INCR increases the number stored at key by 1.

INCRBY increases the number by a specific amount.

Examples
Increase the count of page_views by 1.
Redis
INCR page_views
Add 5 to the likes counter.
Redis
INCRBY likes 5
Decrease the visitors count by 1.
Redis
DECR visitors
Get the current count of page_views.
Redis
GET page_views
Sample Program

This example counts visits. It adds 1 twice, then adds 3 more, then shows the total.

Redis
INCR visits
INCR visits
INCRBY visits 3
GET visits
OutputSuccess
Important Notes

If the key does not exist, INCR starts it at 0 before adding.

Counters are stored as strings but behave like numbers for these commands.

Use DECR to reduce the count if needed.

Summary

The counter pattern uses Redis commands like INCR to count things easily.

It is fast and simple for tracking numbers like visits or likes.

Remember to use GET to see the current count.