0% found this document useful (0 votes)
3 views21 pages

Redis Guide Java

Uploaded by

vivek
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views21 pages

Redis Guide Java

Uploaded by

vivek
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Redis Complete Guide for Java Backend Developers

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.

Why Redis Matters for Java Developers


In a typical Spring Boot microservices architecture, Redis fills several critical roles: distributed
caching (replacing Ehcache or Caffeine), session storage (replacing sticky sessions), pub/sub
messaging (lightweight alternative to Kafka for simple use cases), distributed locks (solving cross-
instance concurrency), and rate limiting — all with a single dependency.

1.1 Key Characteristics


• In-memory storage: All data lives in RAM — reads/writes are O(1) to O(log N) depending on
operation
• Persistence options: RDB snapshots and AOF (Append-Only File) logging for durability
• Single-threaded command execution: Eliminates locking complexity, guarantees atomicity
• Rich data types: Strings, Hashes, Lists, Sets, Sorted Sets, Streams, HyperLogLog, Bitmaps,
Geo
• Replication & Clustering: Master-replica replication, Redis Cluster for horizontal scaling
• Lua scripting: Atomic multi-step operations with server-side scripts

1.2 Redis vs. Other Technologies

Feature Redis Memcached Ehcache Hazelcast


Data Types Rich (10+ types) Strings only Java objects Java objects
Persistence Yes (RDB/AOF) No Optional Yes
Pub/Sub Yes No No Yes

Page 1 of 21
Redis Complete Guide for Java Backend Developers

Cluster Native Client-side No (basic) Yes


Transactions Yes No No Yes
(MULTI/EXEC)
TTL/Expiry Per-key TTL Per-key TTL Yes Yes
Java Client Jedis/Lettuce SpyMemcac Native Native API
hed

2. Redis Data Types — Deep Dive


Redis is not just a key-value store. Understanding its data types is the foundation of using Redis
effectively. Each type has specific internal encodings that Redis automatically optimizes based on
size.

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

Java with Spring Data Redis


@Autowired
private StringRedisTemplate redisTemplate;

// Set with TTL


[Link]().set("user:1", "Alice", [Link](1));

// Atomic increment

Page 2 of 21
Redis Complete Guide for Java Backend Developers

Long count = [Link]().increment("page:views");

// Get
String val = [Link]().get("user:1");

// Set if absent (NX flag)


Boolean ok = [Link]()
.setIfAbsent("lock:key", "owner", [Link](30));

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

Java with Spring Data Redis


HashOperations<String, String, String> ops = [Link]();

// Store a user object as hash


Map<String, String> userData = new HashMap<>();
[Link]("name", "Alice");
[Link]("age", "30");
[Link]("user:1", userData);

// Get single field


String name = [Link]("user:1", "name");

// Get all as Map


Map<String, String> user = [Link]("user:1");

// Using RedisTemplate with object serialization


@Autowired
private RedisTemplate<String, User> redisTemplate;

Page 3 of 21
Redis Complete Guide for Java Backend Developers

[Link]().put("users", "1", userObject);

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)

Java — Implementing a Simple Task Queue


ListOperations<String, String> ops = [Link]();

// Producer: push task to queue


[Link]("task:queue", taskJson);

// Consumer: blocking pop (waits up to 30s)


String task = [Link]("task:queue", [Link](30));

// Paginated feed (most recent 10)


List<String> feed = [Link]("user:1:feed", 0, 9);

// Reliable queue pattern (atomic move to processing list)


String task = (String) [Link](new SessionCallback<>() {
public Object execute(RedisOperations ops) {
return [Link]()
.rightPopAndLeftPush("queue", "processing");
}
});

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

2.5 Sorted Sets (ZSets)


Like Sets but each member has an associated floating-point score. Members are always sorted by
score. This makes them perfect for leaderboards, priority queues, range queries, and time-series
indexing.

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

Java — Leaderboard Implementation


ZSetOperations<String, String> zOps = [Link]();

// Add/update score

Page 5 of 21
Redis Complete Guide for Java Backend Developers

[Link]("leaderboard", "player1", 1500.0);


[Link]("leaderboard", "player1", 50.0);

// Top 10 players
Set<[Link]<String>> top10 =
[Link]("leaderboard", 0, 9);

[Link](t -> [Link](


[Link]() + " -> " + [Link]()));

// Player rank
Long rank = [Link]("leaderboard", "player1");

// Players in score range


Set<String> mid = [Link]("leaderboard", 1000, 2000);

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

3. Expiry, TTL, and Eviction Policies


3.1 Setting Expiry
SET key value EX 3600 # Expire in 3600 seconds
SET key value PX 3600000 # Expire in 3600000 milliseconds
SET key value EXAT 1700000000 # Expire at Unix timestamp
EXPIRE key 3600 # Set/update TTL on existing key
PEXPIRE key 3600000 # TTL in milliseconds
EXPIREAT key 1700000000 # At Unix timestamp
PERSIST key # Remove TTL (make permanent)
TTL key # Remaining TTL in seconds (-1=never, -2=gone)
PTTL key # Remaining TTL in milliseconds

3.2 Eviction Policies


When Redis reaches its maxmemory limit, it evicts keys based on the configured policy. Set in
[Link] or via CONFIG SET maxmemory-policy.

Policy Description Best Use Case

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

4. Persistence: RDB and AOF


4.1 RDB (Redis Database Snapshot)
RDB creates point-in-time snapshots of the entire dataset. Redis forks a child process to write the
snapshot to disk without blocking the main thread.
• Pros: Compact single file, fast restarts, good for backups
• Cons: Data between snapshots can be lost on crash

RDB Configuration ([Link])


save 900 1 # Snapshot if 1+ key changed in 900s
save 300 10 # Snapshot if 10+ keys changed in 300s
save 60 10000 # Snapshot if 10000+ keys changed in 60s
dbfilename [Link]
dir /var/redis/data
rdbcompression yes

4.2 AOF (Append-Only File)


AOF logs every write command. On restart, Redis replays the log to reconstruct the dataset. More
durable than RDB.
• Pros: Much more durable, configurable fsync frequency, human-readable log
• Cons: Larger files, slower restart, slightly lower throughput

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

appendfsync no # OS decides (fastest, least safe)


auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb

Recommendation for Java Microservices


Use AOF with appendfsync everysec for most production use cases. It gives you at most 1 second of
data loss on crash with minimal performance impact. For pure caching scenarios with Redis as a
secondary store, RDB-only or even no persistence is acceptable.

4.3 RDB + AOF Hybrid


Redis 4.0+ supports hybrid persistence: AOF file starts with an RDB snapshot for fast loading,
followed by AOF deltas for durability.
aof-use-rdb-preamble yes # Enable hybrid (default in 5.0+)

5. Transactions and Atomic Operations


5.1 MULTI/EXEC Transactions
Redis transactions queue commands and execute them atomically. Unlike SQL, Redis transactions
don't support rollback on runtime errors — they only prevent execution on syntax errors during
MULTI.
MULTI # Start transaction
SET balance 1000
DECRBY balance 100
INCRBY savings 100
EXEC # Execute all queued commands atomically

# Discard a transaction
MULTI
SET temp "value"
DISCARD # Cancel

5.2 WATCH — Optimistic Locking


WATCH implements optimistic locking: if a watched key changes before EXEC, the transaction
aborts (EXEC returns nil). You then retry the transaction.
WATCH balance # Watch the key
val = GET balance # Read current value
# ... compute new value ...
MULTI
SET balance newValue
EXEC # Returns nil if balance changed since WATCH

Page 9 of 21
Redis Complete Guide for Java Backend Developers

Java — Optimistic Locking with Spring Data


[Link](new SessionCallback<Object>() {
public Object execute(RedisOperations ops) {
[Link]("balance");
String balance = (String) [Link]().get("balance");
int newBalance = [Link](balance) - 100;
[Link]();
[Link]().set("balance", [Link](newBalance));
return [Link](); // null if key changed
}
});

5.3 Lua Scripting


Lua scripts run atomically on the Redis server. They're ideal for complex read-modify-write
operations that require multiple commands without interference.

Example: Atomic Rate Limiter in Lua


-- Lua script: increment counter, set TTL if new, return current count
local current = [Link]('INCR', KEYS[1])
if current == 1 then
[Link]('EXPIRE', KEYS[1], ARGV[1])
end
return current

Java — Running Lua Scripts


DefaultRedisScript<Long> script = new DefaultRedisScript<>();
[Link](
"local c = [Link]('INCR', KEYS[1])\n" +
"if c == 1 then [Link]('EXPIRE', KEYS[1], ARGV[1]) end\n" +
"return c"
);
[Link]([Link]);

Long count = [Link](script,


[Link]("rate:user:42"),
"60" // TTL 60 seconds
);

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

6.2 Java — Spring Data Redis Pub/Sub


// Publisher
@Service
public class OrderPublisher {
@Autowired RedisTemplate<String, String> redisTemplate;

public void publish(String channel, Object message) {


[Link](channel, toJson(message));
}
}

// Subscriber (message listener)


@Component
public class OrderListener implements MessageListener {
@Override
public void onMessage(Message message, byte[] pattern) {
String body = new String([Link]());
// handle body
}
}

// 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

7. Spring Boot Integration


7.1 Maven Dependencies
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- Lettuce (default, non-blocking) is included automatically -->


<!-- For Jedis (blocking, connection pool): -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>jedis</artifactId>
</dependency>

7.2 [Link] Configuration


spring:
data:
redis:
host: localhost
port: 6379
password: yourpassword
database: 0
timeout: 2000ms
lettuce:
pool:
max-active: 20
max-idle: 10
min-idle: 5
max-wait: -1ms
# For cluster:
# cluster:
# nodes: node1:7000,node2:7001,node3:7002
# For sentinel:
# sentinel:
# master: mymaster
# nodes: sentinel1:26379,sentinel2:26379

7.3 RedisTemplate Configuration


@Configuration
public class RedisConfig {

@Bean

Page 12 of 21
Redis Complete Guide for Java Backend Developers

public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory f) {


RedisTemplate<String, Object> tpl = new RedisTemplate<>();
[Link](f);

// Key serializer: human-readable strings


[Link](new StringRedisSerializer());
[Link](new StringRedisSerializer());

// Value serializer: JSON (Jackson)


Jackson2JsonRedisSerializer<Object> json =
new Jackson2JsonRedisSerializer<>([Link]);
[Link](json);
[Link](json);

[Link]();
return tpl;
}
}

7.4 Spring Cache Abstraction (@Cacheable)


Spring's @Cacheable annotation integrates transparently with Redis, letting you cache method
results without touching Redis APIs directly.
// Enable caching in main class or config
@EnableCaching
@SpringBootApplication
public class App { }

// 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

@Cacheable(value = "users", key = "#id")


public User getUser(Long id) {
return [Link](id).orElseThrow();
}

@CachePut(value = "users", key = "#[Link]")


public User updateUser(User user) {
return [Link](user);
}

@CacheEvict(value = "users", key = "#id")


public void deleteUser(Long id) {
[Link](id);
}

@CacheEvict(value = "users", allEntries = true)


public void clearAllUsers() { }
}

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;

Product product = [Link](id).orElseThrow();


[Link]().set(key, product, [Link](1));
return product;
}

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

8.3 Write-Behind (Write-Back)


The application writes to Redis immediately and asynchronously persists to the DB later. Very high
write throughput but risk of data loss. Best with persistence-backed Redis.

8.4 Cache Stampede / Dog-piling Prevention


When many requests miss the cache simultaneously and all hit the DB together. Solution:
probabilistic early recomputation or a distributed lock.
// Using a distributed lock to prevent stampede
public Product getProduct(Long id) {
String key = "product:" + id;
Product cached = (Product) [Link]().get(key);
if (cached != null) return cached;

String lockKey = "lock:product:" + id;


boolean locked = [Link](
[Link]().setIfAbsent(lockKey, "1", [Link](5)));
if (!locked) {
[Link](100);
return getProduct(id); // retry
}
try {
Product p = [Link](id).orElseThrow();
[Link]().set(key, p, [Link](1));
return p;
} finally {
[Link](lockKey);
}
}

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.

Simple Lock with Spring Data


public boolean acquireLock(String lockKey, String clientId, long ttlMs) {
return [Link](

Page 15 of 21
Redis Complete Guide for Java Backend Developers

[Link]()
.setIfAbsent(lockKey, clientId, [Link](ttlMs)));
}

// IMPORTANT: only release YOUR lock (Lua for atomicity)


private static final String RELEASE_SCRIPT =
"if [Link]('get', KEYS[1]) == ARGV[1] then" +
" return [Link]('del', KEYS[1])" +
"else return 0 end";

public boolean releaseLock(String lockKey, String clientId) {


DefaultRedisScript<Long> script = new DefaultRedisScript<>(RELEASE_SCRIPT,
[Link]);
Long result = [Link](script,
[Link](lockKey), clientId);
return [Link](1L).equals(result);
}

9.2 Rate Limiting


Redis is ideal for implementing API rate limiting across multiple service instances. The token bucket
and sliding window patterns are commonly used.

Fixed Window Rate Limiter


@Service
public class RateLimiterService {
@Autowired RedisTemplate<String, String> tpl;

public boolean isAllowed(String userId, int maxRequests, int windowSeconds) {


String key = "rate:" + userId + ":" + ([Link]() /
(windowSeconds * 1000));
Long count = [Link]().increment(key);
if (count == 1) {
[Link](key, [Link](windowSeconds));
}
return count <= maxRequests;
}
}

9.3 Session Storage


Use Spring Session with Redis to store HTTP sessions in Redis, enabling stateless, horizontally
scalable services.
<!-- [Link] -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-session-data-redis</artifactId>

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 { }

// That's it — HttpSession now backed by Redis automatically

10. Cluster & High Availability


10.1 Replication (Master-Replica)
Redis supports asynchronous master-replica replication. Replicas can serve read traffic, reducing
load on the master. Failover is manual unless Redis Sentinel is used.
# In replica's [Link]:
replicaof master-host 6379
replica-read-only yes

# Check replication status


INFO replication

10.2 Redis Sentinel


Sentinel provides automatic failover: it monitors masters and replicas, promotes a replica if the
master fails, and notifies clients of the new master. Use at least 3 Sentinel instances.
# [Link]
sentinel monitor mymaster [Link] 6379 2 # quorum = 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000

# Spring Boot [Link]


spring:
data:
redis:
sentinel:

Page 17 of 21
Redis Complete Guide for Java Backend Developers

master: mymaster
nodes: sentinel1:26379,sentinel2:26379,sentinel3:26379

10.3 Redis Cluster


Redis Cluster provides horizontal scaling by automatically sharding data across multiple nodes
using hash slots (16384 total). Each master handles a range of slots. Data is automatically
rebalanced when nodes are added/removed.
• Minimum recommended: 6 nodes (3 masters + 3 replicas)
• Keys are distributed via CRC16(key) % 16384
• Hash tags {tag} force co-location: {user:1}:profile and {user:1}:settings go to same slot
• Multi-key commands (MGET, MSET) only work if all keys are in the same slot

# Create a cluster
redis-cli --cluster create \
host1:7000 host1:7001 \
host2:7000 host2:7001 \
host3:7000 host3:7001 \
--cluster-replicas 1

# Spring Boot [Link]


spring:
data:
redis:
cluster:
nodes: host1:7000,host1:7001,host2:7000,host2:7001
max-redirects: 3

11. Performance Tuning & Monitoring


11.1 Key Naming Conventions
• Use colon-separated hierarchical names: entity:id:field
• Examples: user:42:profile, order:2024:status, session:abc123
• Keep key names short but meaningful — they consume memory
• Use hash tags for cluster co-location: {userId}:cart, {userId}:wishlist

11.2 Important Redis CLI Commands for Ops


INFO all # Full server statistics
INFO memory # Memory stats
INFO stats # Operation stats
INFO keyspace # DB key counts

Page 18 of 21
Redis Complete Guide for Java Backend Developers

INFO replication # Replication status


CONFIG GET maxmemory # Check config
CONFIG SET maxmemory 2gb # Change config live
DBSIZE # Total key count
MONITOR # Real-time command log (dev only!)
SLOWLOG GET 10 # Last 10 slow commands
SLOWLOG RESET
CLIENT LIST # Connected clients
DEBUG SLEEP 0 # Latency test
LATENCY HISTORY event # Latency history
MEMORY USAGE key # Memory for specific key
OBJECT ENCODING key # Internal encoding
SCAN 0 MATCH user:* COUNT 100 # Safe key scanning (never use KEYS * in prod!)

11.3 Pipeline & Batching


Pipelining sends multiple commands in one network round-trip, drastically reducing latency for bulk
operations.
// Pipeline in Spring Data Redis
List<Object> results = [Link](new SessionCallback<>() {
public Object execute(RedisOperations ops) {
for (int i = 0; i < 1000; i++) {
[Link]().set("key:" + i, "value:" + i);
}
return null;
}
});

11.4 Connection Pooling (Lettuce)


spring:
data:
redis:
lettuce:
pool:
max-active: 50 # Max connections
max-idle: 20 # Max idle
min-idle: 5 # Min idle
max-wait: 2000ms # Max wait for connection
time-between-eviction-runs: 60s

11.5 Common Performance Anti-Patterns


• KEYS * in production: Blocks server! Use SCAN instead
• Large values: Avoid storing multi-MB objects; split or compress
• No TTLs on cache keys: Memory leak; always set expiry for cache

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

12. Security Best Practices


12.1 Authentication & Network
# [Link]
requirepass yourStrongPassword123!
bind [Link] # Only listen on loopback (or specific IPs)
protected-mode yes
port 6379
rename-command FLUSHALL "" # Disable dangerous commands
rename-command CONFIG "SAFECONFIG"
rename-command DEBUG ""
rename-command MONITOR ""

12.2 Redis ACL (Redis 6+)


Access Control Lists let you define per-user permissions on commands and key patterns.
# Create users
ACL SETUSER appuser on >password ~cache:* +GET +SET +DEL +EXPIRE
ACL SETUSER readonly on >ropass ~* +@read
ACL LIST # List all users
ACL WHOAMI # Current user

# [Link] with user


spring:
data:
redis:
username: appuser
password: password

13. Quick Reference Cheatsheet

Use Case Data Type / Pattern Key Command(s)


Session storage String SET key val EX ttl / GET
User profile fields Hash HSET / HGET / HGETALL

Page 20 of 21
Redis Complete Guide for Java Backend Developers

Activity feed / Queue List RPUSH / BLPOP / LRANGE


Unique tags / friends Set SADD / SISMEMBER / SINTER
Leaderboard / ranking Sorted Set ZADD / ZREVRANGE / ZRANK
Approx unique visitors HyperLogLog PFADD / PFCOUNT
Daily active users Bitmap SETBIT / BITCOUNT
Geolocation search Geo GEOADD / GEOSEARCH
Event log / Kafka-lite Stream XADD / XREADGROUP / XACK
Distributed lock String + NX SET key val NX PX ttl
Rate limiting String + INCR INCR / EXPIRE
Pub/Sub messaging Pub/Sub PUBLISH / SUBSCRIBE
Atomic multi-step ops Lua / MULTI EVAL / MULTI+EXEC
Object caching @Cacheable Spring Cache abstraction

Redis Complete Guide — Built for Java Backend Developers

Page 21 of 21

You might also like