What is List in Redis: Explanation and Usage Examples
list is a collection of ordered strings that allows you to add, remove, and access elements from both ends efficiently. It works like a simple queue or stack, making it useful for tasks like messaging or task management.How It Works
Think of a Redis list as a line of people waiting at a store. You can add people to the front or back of the line, and you can also remove people from either end. This makes it very flexible for different scenarios.
Internally, Redis stores lists as linked lists or compressed lists depending on their size, which allows fast operations at both ends. You can push new items to the start or end, pop items from either side, or even get elements by their position.
This ordered structure means you always know the sequence of elements, which is great for queues, stacks, or any situation where order matters.
Example
This example shows how to create a list, add items to it, and retrieve them using Redis commands.
LPUSH tasks "task1" LPUSH tasks "task2" RPUSH tasks "task3" LRANGE tasks 0 -1
When to Use
Use Redis lists when you need an ordered collection of strings with fast insertion and removal from both ends. Common use cases include:
- Implementing queues for background jobs or messaging systems.
- Maintaining recent activity logs or timelines.
- Building stacks for undo functionality or navigation history.
Because Redis lists are simple and fast, they are ideal for real-time applications where order and speed matter.
Key Points
- Redis lists store ordered strings accessible from both ends.
- They support fast push and pop operations at the start or end.
- Lists are useful for queues, stacks, and ordered logs.
- Commands like
LPUSH,RPUSH, andLRANGEmanage lists.