Redis
Li Wei
Redis
Preface
Shang Silicon Valley mind map (download to view):
Mind map summary: https://www.zhixi.com/view/a87cd3db
Getting Started
SQL and NoSQL
Redis is a key‑value NoSQL database. Two key terms here:
- Key‑value
- NoSQL
Key‑value means that data in Redis is stored as key‑value pairs, and the value can take many forms—strings, numbers, even JSON.
NoSQL refers to databases that differ significantly from traditional relational databases. They impose far fewer constraints on stored data—no strict uniqueness, nullable rules, etc.—so we call them “NoSQL” (Not Only SQL) or simply “non‑SQL” databases, i.e., non‑relational databases.
Comparison
Structured vs. Unstructured
Relational databases store structured data with strict schema (field names, types, constraints). NoSQL databases have loose, flexible schemas; they can be key‑value, document, graph, etc.Relations vs. No Relations
Relational tables often have foreign‑key relationships. Non‑relational databases lack built‑in relations; any relationships must be handled in application code.Transactions
Relational databases support ACID transactions. Most NoSQL databases either do not support transactions or provide only limited consistency guarantees.Storage
Relational databases rely heavily on disk I/O, which can affect performance. Non‑relational databases operate primarily in memory, giving them much faster read/write speeds.Scalability
Relational clusters are usually master‑slave (vertical scaling). Non‑relational databases can shard data across many machines (horizontal scaling), allowing massive data volumes despite limited memory per node. Horizontal scaling is harder for relational databases because of inter‑table relationships.
In short:
Redis is an in‑memory key‑value NoSQL database. Its full name is Remote Dictionary Server.
Official site: https://redis.io/
Features
- Key‑value store; values support many data structures
- Single‑threaded; each command is atomic
- Low latency, high speed (in‑memory, I/O multiplexing, efficient encoding)
- Persistence support
- Master‑slave and sharded clustering
- Multi‑language clients
Common Commands
Overview
Redis is a key-value database. Keys are usually strings, but values can be of many types.
Redis groups commands by the data type they operate on; you can view all commands on the official site or run them inside a container.
Command reference: https://redis.io/commands
Generic Commands
These commands work across multiple data types:
KEYS– list all keys matching a patternDEL– delete a specific keyEXISTS– test whether a key existsEXPIRE– set an expiration time for a key (the key is deleted automatically when it expires)TTL(Time To Live) – view the remaining TTL of a key
Use help [command] to see detailed usage of a command.
Code examples
KEYSNote: In production, avoid the
keyscommand because it is inefficient when there are many keys.DELNote: When copying code, only copy the relevant command.
EXISTSEXPIRENote: Memory is precious; set expiration times for data that can be removed automatically when it expires.
ACL Commands
Redis ACL stands for Access Control List. It lets you restrict connections based on allowed commands and accessible keys.
acl cat– view added permission categoriesacl whoami– view the current useracl setuser username on >password ~cached:* +get– set a user with username, password, and ACL permissions (e.g., onlyGET)
Core Data Types
String
The simplest Redis type; values are strings, which can be:
string– plain stringint– integer (supports increment/decrement)float– floating‑point number (supports increment/decrement)
Common String commands:
SET– set or update a String key‑value pairGET– get the value of a String keyMSET– batch add multiple String key‑value pairsMGET– get values of multiple String keysINCR– increment an integer key by 1INCRBY– increment an integer key by a specified step (e.g.,incrby num 2incrementsnumby 2)INCRBYFLOAT– increment a floating‑point key by a specified step (step must be provided)SETNX(set if not exists) – add a String key‑value pair only if the key does not existSETEX(set with expiration) – add a String key‑value pair and set its TTL
All commands except INCRBYFLOAT are common; some combined commands include SETNX and SETEX.
Code examples
SETandGET– add if absent, otherwise updateMSETandMGETINCR,INCRBY, andDECYSETNXSETEX
Hash
A hash (or map) stores an unordered dictionary, similar to Java’s HashMap. Unlike storing a whole object as a JSON string (which makes field updates cumbersome), a hash lets you store each field separately and perform CRUD on individual fields.
Common Hash commands
HSET key field value– set or update a field in a hash keyHGET key field– get a field’s value from a hash keyHMSET key field1 value1 [field2 value2 ...]– batch get multiple fields from a hash keyHGETALL key– get all fields and values of a hash keyHKEYS key– get all fields of a hash keyHVALS key– get all values of a hash keyHINCRBY key field increment– increment a field’s value by a stepHSETNX key field value– add a field only if it does not exist
Code examples
HSETandHGETHMSETandHMGETHGETALLHKEYSandHVALSHINCRBYHSETNX
List
Redis lists are similar to Java’s LinkedList—a doubly linked list that supports both forward and reverse traversal.
Characteristics (like LinkedList):
- Ordered
- Duplicate elements allowed
- Fast insertion/deletion
- Average lookup speed
Typical use cases: ordered collections such as “likes” lists, comment streams, etc.
Common List commands
LPUSH key element ...– push one or more elements to the left (head)LPOP key– pop and return the leftmost element (ornilif empty)RPUSH key element ...– push one or more elements to the right (tail)RPOP key– pop and return the rightmost elementLRANGE key start end– get a range of elements by start and end indexesBLPOPandBRPOP– likeLPOP/RPOPbut block for a specified time when the list is empty, instead of returningnil
Code examples
LPUSHandRPUSHLPOPandRPOPLRANGE
Set
Redis sets are analogous to Java’s HashSet—a collection of unique values (the underlying structure is a hash table with null values).
Features:
- Unordered
- No duplicate elements
- Fast lookups
- Support for set operations (intersection, union, difference)
Common Set commands
SADD key member ...– add one or more members to a setSREM key member ...– remove specific members from a setSCARD key– get the number of members in a setSISMEMBER key member– test membership of an elementSMEMBERS– retrieve all members of a setSINTER key1 key2 ...– compute the intersection ofkey1andkey2SDIFF key1 key2 ...– compute the difference ofkey1andkey2SUNION key1 key2 ...– compute the union ofkey1andkey2
Example
Two sets: s1 and s2:
- Intersection:
SINTER s1 s2 - Difference (
s1vss2):SDIFF s1 s2
ZSet (Sorted Set)
Redis Sorted Sets are ordered sets, similar in concept to Java’s TreeSet but implemented differently. Each element carries a score (score) attribute, and elements are ordered by this score using a skip list plus a hash table.
Properties:
- Ordered
- Unique elements
- Fast range queries
Sorted Sets are often used for leaderboards.
Common Sorted Set commands
ZADD key score member– add one or more members with scores (updates score if member exists)ZREM key member– remove a specific memberZSCORE key member– get the score of a memberZRANK key member– get the rank (position) of a memberZCARD key– get the number of membersZCOUNT key min max– count members with scores within a given rangeZINCRBY key increment member– increment a member’s score by a specified amountZRANGE key min max– get members within a rank range (ordered by score)ZRANGEBYSCORE key min max– get members within a score rangeZDIFF.ZINTER.ZUNION– compute difference, intersection, union
All ranks are ascending by default; add REV after the Z command to get descending order.
Examples:
- Ascending rank:
ZRANK key member - Descending rank: ⟟TOK93⟧
Clients
Monitor
MONITOR turns a client into a monitor that receives and prints real‑time information about commands the server processes. Each time the server handles a command, it calls replicationFeedMonitors, which sends the command details to all monitors.
Code example
(omitted)
Jedis
Overview
Redis provides official clients for many languages.
Official site: https://redis.io/docs/clients/
Java clients include:
- Jedis and Lettuce – provide direct API mappings for Redis commands; Spring Data Redis abstracts them.
- Redisson – builds distributed, scalable Java data structures on top of Redis (e.g.,
Map.Queue) and supports cross‑process synchronization primitives such asLock.Semaphore, useful for special functional requirements.
Quick Start
Steps:
- Add the dependency.
- Create a connection (e.g., in a unit‑test class).
- Run tests.
- Release resources.
Connection Pool
Jedis is not thread‑safe, and repeatedly creating/destroying connections hurts performance. Use a Jedis connection pool instead of direct connections.
Pooling is a common pattern (e.g., DB connection pools, Tomcat thread pools).
Creating a Jedis pool
(code omitted)
Explanation
JedisConnectionFacotry– the Factory pattern reduces coupling (e.g., Spring bean creation).- Static initializer block – runs once when the class loads, initializing the pool.
- Provide a method to fetch a connection from the pool.
- When using the pool, “closing” a connection actually returns it to the pool.
Spring Data Redis
Overview
Spring Data is Spring’s data‑access module, providing integration with many databases. Its Redis integration is called Spring Data Redis.
Official site: https://spring.io/projects/spring-data-redis
Features:
- Integrates multiple Redis clients (Lettuce, Jedis)
- Unified
RedisTemplateAPI - Pub/Sub support
- Sentinel and cluster support
- Reactive programming with Lettuce
- Serialization/deserialization for JDK objects, JSON, strings, and Spring objects
- JDK collection implementations backed by Redis
RedisTemplate encapsulates various Redis operations, with type‑specific APIs.
Quick Start
Spring Boot already includes Spring Data Redis support.
- Add the Maven coordinates.
- Configure in
application.yml. - Autowire
RedisTemplateand test.
Serializers
RedisTemplate can store any Object as a value, but it serializes objects using Java’s default serialization, which is verbose and memory‑heavy.
Custom serializer example (JSON)
(code omitted)
The result is much more readable, automatically converting Java objects to JSON strings and back.
StringRedisTemplate
While JSON serialization works, it adds class metadata to each entry, increasing memory usage. To reduce overhead, you can use manual (e.g., plain string) serialization instead of the default serializer.
Originally written by Li Wei (李唯_) and published in Chinese on 后端技术栈全书 (Full-Stack Backend Engineering). Translated and adapted for DriftSeas with permission.