Redis Guide Java
Redis Guide Java
REDIS
The Complete Guide for Java Backend Developers
Data Structures · Caching · Pub/Sub · Streams · Clustering · Spring Integration
1. What is Redis?
Redis (Remote Dictionary Server) is an open-source, in-memory data structure store used as a
database, cache, message broker, and streaming engine. Redis stores data in RAM, making it
blazing fast — capable of processing millions of requests per second with sub-millisecond latency.
Page 1 of 21
Redis Complete Guide for Java Backend Developers
2.1 Strings
The most basic type. A Redis string can store text, integers, floats, or raw binary data. Maximum
size is 512 MB.
Common Commands
SET user:1:name "Alice" # Store a string
GET user:1:name # Retrieve
SET counter 100 # Integer stored as string
INCR counter # Atomic increment → 101
INCRBY counter 50 # Increment by 50 → 151
DECR counter # Decrement → 150
SETEX session:abc 3600 "data" # Set with TTL (seconds)
SET session:abc "data" EX 3600 # Same, modern syntax
SETNX lock:resource "owner" # Set if Not Exists (distributed lock)
GETSET key newValue # Get old, set new (atomic)
MSET k1 v1 k2 v2 k3 v3 # Multi-set
MGET k1 k2 k3 # Multi-get
STRLEN user:1:name # String length
APPEND log:today " new-entry" # Append to string
// Atomic increment
Page 2 of 21
Redis Complete Guide for Java Backend Developers
// Get
String val = [Link]().get("user:1");
2.2 Hashes
Hashes store field-value pairs, like a Java Map<String, String>. Ideal for representing objects
(users, products) without serializing the whole object. You can update individual fields without
overwriting the whole value.
Common Commands
HSET user:1 name "Alice" age "30" email "alice@[Link]"
HGET user:1 name # "Alice"
HMGET user:1 name email # Multiple fields
HGETALL user:1 # All fields + values
HKEYS user:1 # Just field names
HVALS user:1 # Just values
HLEN user:1 # Number of fields
HDEL user:1 email # Remove a field
HEXISTS user:1 name # Check existence (0 or 1)
HINCRBY user:1 loginCount 1 # Atomic increment on field
HSCAN user:1 0 MATCH * COUNT 100 # Iterate large hashes
Page 3 of 21
Redis Complete Guide for Java Backend Developers
2.3 Lists
Redis Lists are linked lists of strings. They support push/pop from both ends, making them ideal for
queues, stacks, activity feeds, and task queues.
Common Commands
LPUSH queue:tasks "task3" # Push to LEFT (head)
RPUSH queue:tasks "task4" # Push to RIGHT (tail)
LPOP queue:tasks # Pop from LEFT
RPOP queue:tasks # Pop from RIGHT
BLPOP queue:tasks 30 # Blocking pop, wait 30s
BRPOP queue:tasks 0 # Blocking pop, wait forever
LRANGE queue:tasks 0 -1 # Get all elements (0 to end)
LRANGE queue:tasks 0 9 # First 10 elements
LLEN queue:tasks # Length
LINDEX queue:tasks 0 # Get by index
LINSERT queue:tasks BEFORE "t2" "t1" # Insert before element
LREM queue:tasks 0 "old-task" # Remove all occurrences
LTRIM queue:tasks 0 99 # Trim to first 100 items
RPOPLPUSH src dst # Move element atomically (reliable queue)
Page 4 of 21
Redis Complete Guide for Java Backend Developers
2.4 Sets
Unordered collections of unique strings. Sets support efficient membership tests and set operations
(union, intersection, difference). Great for tags, unique visitors, friend lists.
Common Commands
SADD tags:post:1 "java" "redis" "spring" # Add members
SREM tags:post:1 "spring" # Remove member
SISMEMBER tags:post:1 "java" # Is member? (0 or 1)
SMISMEMBER tags:post:1 "java" "python" # Multi membership check
SMEMBERS tags:post:1 # All members
SCARD tags:post:1 # Cardinality (count)
SPOP tags:post:1 # Pop random member
SRANDMEMBER tags:post:1 3 # Get 3 random (no remove)
SUNION tags:post:1 tags:post:2 # Union of two sets
SINTER tags:post:1 tags:post:2 # Intersection
SDIFF tags:post:1 tags:post:2 # Difference (in 1, not 2)
SUNIONSTORE dest s1 s2 # Store union result
SMOVE src dst member # Move member between sets
Common Commands
ZADD leaderboard 1500.0 "player1" # Add with score
ZADD leaderboard NX 2000.0 "player2" # Add only if not exists
ZADD leaderboard XX GT 2100.0 "player2" # Update only if greater
ZSCORE leaderboard "player1" # Get score
ZINCRBY leaderboard 50.0 "player1" # Increment score
ZRANK leaderboard "player1" # Rank (0-based, ascending)
ZREVRANK leaderboard "player1" # Rank (descending)
ZRANGE leaderboard 0 -1 WITHSCORES # All, asc, with scores
ZREVRANGE leaderboard 0 9 WITHSCORES # Top 10, desc with scores
ZRANGEBYSCORE lb 1000 2000 WITHSCORES # By score range
ZRANGEBYLEX lb "[a" "[m" # By lex range (equal scores)
ZCOUNT leaderboard 1000 2000 # Count in score range
ZREM leaderboard "player1" # Remove member
ZPOPMAX leaderboard 3 # Pop 3 highest
ZPOPMIN leaderboard # Pop lowest
// Add/update score
Page 5 of 21
Redis Complete Guide for Java Backend Developers
// Top 10 players
Set<[Link]<String>> top10 =
[Link]("leaderboard", 0, 9);
// Player rank
Long rank = [Link]("leaderboard", "player1");
2.6 Streams
Redis Streams (introduced in 5.0) is an append-only log data structure. It's similar to Apache Kafka
— ideal for event sourcing, audit logs, and message queuing with consumer groups.
Common Commands
XADD events * action "login" userId "42" # Append event (auto ID)
XADD events 1700000000000-0 field val # Explicit ID
XLEN events # Count entries
XRANGE events - + # All entries
XRANGE events - + COUNT 10 # First 10
XREVRANGE events + - COUNT 10 # Last 10
XREAD COUNT 10 STREAMS events 0 # Read from beginning
XREAD BLOCK 0 STREAMS events $ # Block, listen for new
XGROUP CREATE events grp1 $ # Create consumer group
XREADGROUP GROUP grp1 consumer1 COUNT 5 STREAMS events > # Read undelivered
XACK events grp1 1700000000000-0 # Acknowledge processed
XPENDING events grp1 - + 10 # Pending (unacked) entries
XCLAIM events grp1 consumer2 60000 id # Claim stale message
XTRIM events MAXLEN 10000 # Trim to 10k entries
2.7 HyperLogLog
HyperLogLog is a probabilistic data structure for counting unique elements with very low memory
(~12 KB regardless of cardinality). It gives ~0.81% standard error. Perfect for approximate unique
visitor counts, unique searches, etc.
PFADD unique:visitors "user:1" "user:2" "user:3"
PFADD unique:visitors "user:1" # Duplicate, not counted again
PFCOUNT unique:visitors # Approximate cardinality
PFMERGE combined site1 site2 site3 # Merge multiple HLL keys
Page 6 of 21
Redis Complete Guide for Java Backend Developers
2.8 Bitmaps
Bitmaps are bit arrays stored in strings. Extremely memory-efficient for boolean flags indexed by
integer ID. Example: track daily active users where bit N = 1 means user N was active.
SETBIT active:2024-01-15 42 1 # User 42 was active
GETBIT active:2024-01-15 42 # Was user 42 active?
BITCOUNT active:2024-01-15 # Total active users
BITOP AND result day1 day2 # Active on both days
BITOP OR result day1 day2 # Active on any day
BITPOS active:2024-01-15 1 # First active user
2.9 Geospatial
Redis can store longitude/latitude coordinates and perform distance calculations. Internally stored
as sorted sets with geohash scores.
GEOADD locations 77.2090 28.6139 "Delhi"
GEOADD locations 72.8777 19.0760 "Mumbai"
GEODIST locations "Delhi" "Mumbai" km # Distance in km
GEOPOS locations "Delhi" # Get coordinates
GEOSEARCH locations FROMMEMBER "Delhi" BYRADIUS 500 km ASC
GEOHASH locations "Delhi" # Get geohash string
Page 7 of 21
Redis Complete Guide for Java Backend Developers
noeviction Return error when memory full When data loss is unacceptable
allkeys-lru Evict least recently used key from all General caching
volatile-lru Evict LRU only from keys with TTL Mixed persistent + cache
allkeys-lfu Evict least frequently used from all Skewed access patterns
volatile-lfu Evict LFU only from TTL keys Mixed with hot/cold data
allkeys-random Evict random key from all Rarely used
volatile-random Evict random key with TTL Rarely used
volatile-ttl Evict key with shortest remaining When TTL reflects priority
TTL
AOF Configuration
appendonly yes
appendfsync always # fsync after every command (safest, slowest)
appendfsync everysec # fsync every second (recommended balance)
Page 8 of 21
Redis Complete Guide for Java Backend Developers
# Discard a transaction
MULTI
SET temp "value"
DISCARD # Cancel
Page 9 of 21
Redis Complete Guide for Java Backend Developers
Page 10 of 21
Redis Complete Guide for Java Backend Developers
6. Pub/Sub Messaging
6.1 Basic Pub/Sub
Redis Pub/Sub implements a fire-and-forget messaging pattern. Publishers send messages to
channels, and all subscribers receive them. Messages are not persisted — if a subscriber is offline,
it misses the message.
SUBSCRIBE orders notifications # Subscribe to channels
PSUBSCRIBE order.* # Pattern subscribe (glob)
PUBLISH orders "{\"id\":1, \"status\":\"PLACED\"}" # Publish
UNSUBSCRIBE orders # Unsubscribe
PUBSUB CHANNELS # List active channels
PUBSUB NUMSUB orders # Subscriber count per channel
// Configuration
@Bean
public RedisMessageListenerContainer listenerContainer(
RedisConnectionFactory factory, OrderListener listener) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
[Link](factory);
[Link](listener, new ChannelTopic("orders"));
return container;
}
Page 11 of 21
Redis Complete Guide for Java Backend Developers
@Bean
Page 12 of 21
Redis Complete Guide for Java Backend Developers
[Link]();
return tpl;
}
}
// Cache configuration
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config = [Link]()
.entryTtl([Link](30))
.serializeValuesWith(
[Link]
.fromSerializer(new Jackson2JsonRedisSerializer<>([Link])));
return [Link](factory)
.cacheDefaults(config)
.withCacheConfiguration("users",
[Link]([Link](1)))
.build();
}
// Usage in service
@Service
public class UserService {
Page 13 of 21
Redis Complete Guide for Java Backend Developers
8. Caching Patterns
8.1 Cache-Aside (Lazy Loading)
The most common pattern. The application checks the cache first; on a miss, it loads from the DB
and populates the cache. Redis is not involved in writes to the DB.
public Product getProduct(Long id) {
String key = "product:" + id;
Product cached = (Product) [Link]().get(key);
if (cached != null) return cached;
8.2 Write-Through
Every write to the DB also writes to the cache. Cache is always fresh, but every write has Redis
overhead.
public Product save(Product product) {
Product saved = [Link](product);
[Link]().set(
"product:" + [Link](), saved, [Link](1));
return saved;
Page 14 of 21
Redis Complete Guide for Java Backend Developers
9. Distributed Patterns
9.1 Distributed Lock (Redlock)
A distributed lock prevents multiple JVM instances from concurrently modifying shared state. The
simplest approach: SET NX PX. For production multi-instance environments, use the Redlock
algorithm via Redisson.
Page 15 of 21
Redis Complete Guide for Java Backend Developers
[Link]()
.setIfAbsent(lockKey, clientId, [Link](ttlMs)));
}
Page 16 of 21
Redis Complete Guide for Java Backend Developers
</dependency>
// [Link]
spring:
session:
store-type: redis
timeout: 30m
redis:
namespace: myapp:sessions
// Config class
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
@Configuration
public class SessionConfig { }
Page 17 of 21
Redis Complete Guide for Java Backend Developers
master: mymaster
nodes: sentinel1:26379,sentinel2:26379,sentinel3:26379
# Create a cluster
redis-cli --cluster create \
host1:7000 host1:7001 \
host2:7000 host2:7001 \
host3:7000 host3:7001 \
--cluster-replicas 1
Page 18 of 21
Redis Complete Guide for Java Backend Developers
Page 19 of 21
Redis Complete Guide for Java Backend Developers
• Storing entire Java objects as JSON when only 2 fields needed: Use Hashes
• Using SMEMBERS on huge Sets: Use SSCAN for large sets
• Synchronous Lettuce calls in reactive stack: Use ReactiveRedisTemplate
Page 20 of 21
Redis Complete Guide for Java Backend Developers
Page 21 of 21