Redis in Spring Boot applications
Redis keeps data in memory and answers in well under a millisecond, which makes it the usual choice for caches, sessions, counters and short-lived locks. Spring Boot connects to it with almost no configuration, but the defaults decide how your objects are stored and what happens when Redis is down. This page runs those parts and shows the data-structure code for Spring Data Redis 4.
Contents
How Spring talks to Redis Connecting, and what happens with no server What actually gets stored: serializers Redis as the Spring cache When Redis is down Data structures with RedisTemplate (not run) Locks, transactions and scripts (not run) Pub/sub and repositories (not run) Running Redis in production Choosing the right Redis feature
How Spring talks to Redis
Redis is a server that keeps keys and values in memory. A value is not just a string: it can be a hash, a list, a set, a sorted set or a stream, and each type has its own commands, such as HSETLPUSHZADD
Spring Data Redis stacks several layers on top of a client library:
| Layer | Class | What it does |
|---|---|---|
| Client | Lettuce 7 (default) or Jedis | Speaks the Redis protocol over the network |
| Connection factory | LettuceConnectionFactory | Creates and shares connections, built from spring.data.redis.* |
| Template | RedisTemplateStringRedisTemplate | Commands per data type, with serializers for keys and values |
| Cache | RedisCacheManager | Backs @Cacheable |
| Messaging | RedisMessageListenerContainer | Publish/subscribe and stream consumers |
| Repositories | @RedisHashCrudRepository | Objects stored as hashes, with secondary indexes |
Adding spring-boot-starter-data-redisRedisTemplate<Object, Object>StringRedisTemplate@EnableCaching
No Redis server is available where this page was built. The four programs shown running are the parts that work without one: the connection setup, the serializers, the cache configuration and the behaviour when Redis cannot be reached. The data-structure, lock and messaging examples are marked as not run; they were checked against the Spring Data Redis reference documentation and the Javadoc of the 4.1 jars.
Connecting, and what happens with no server
A single spring.data.redis.url
package demo.redis.noserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
public class NoServer {
@SpringBootApplication
static class ShopApplication {
}
public static void main(String[] args) {
// nothing listens on port 6390 on this machine
try (var context = SpringApplication.run(ShopApplication.class,
"--spring.main.banner-mode=off", "--logging.level.root=WARN",
"--spring.data.redis.url=redis://shop:secret@localhost:6390/2",
"--spring.data.redis.timeout=2s")) {
System.out.println("Context started without contacting Redis");
var factory = (LettuceConnectionFactory) context.getBean(RedisConnectionFactory.class);
System.out.println("Client: Lettuce, host " + factory.getHostName()
+ ", port " + factory.getPort() + ", database " + factory.getDatabase());
System.out.println("Command timeout: " + factory.getClientConfiguration()
.getCommandTimeout());
StringRedisTemplate redis = context.getBean(StringRedisTemplate.class);
try {
redis.opsForValue().set("greeting", "hello");
} catch (RedisConnectionFailureException e) {
System.out.println("First command: " + e.getClass().getSimpleName());
System.out.println(" " + e.getMessage());
Throwable root = e;
while (root.getCause() != null) {
root = root.getCause();
}
System.out.println(" root cause: " + root.getClass().getSimpleName()
+ ": " + root.getMessage());
}
}
}
}
Context started without contacting Redis
Client: Lettuce, host localhost, port 6390, database 2
Command timeout: PT2S
First command: RedisConnectionFailureException
Unable to connect to Redis
root cause: ConnectException: Connection refused
- The application context started although no Redis server exists. Lettuce connects lazily, on the first command, so a Redis outage does not stop the application from starting.
- The URL
was split into user, password, host, port and database 2. Redis has 16 numbered databases by default; Redis Cluster supports only database 0.redis://shop:secret@localhost:6390/2 became the command timeout. Without it, Lettuce waits 60 seconds for a reply, which is far too long for a cache that should answer in a millisecond.spring.data.redis.timeout=2s- The first command failed with Spring's
, "Unable to connect to Redis", caused by a plainRedisConnectionFailureException . Spring translates client exceptions into itsConnectException: Connection refused hierarchy, so the code does not depend on Lettuce.DataAccessException
The separate properties work too: spring.data.redis.hostportusernamepassworddatabasessl.enabledspring.data.redis.sentinel.*spring.data.redis.cluster.nodesspring.data.redis.lettuce.pool.enabledcommons-pool2
What actually gets stored: serializers
Redis stores bytes. Every Java key and value has to be turned into bytes by a RedisSerializerredis-cli
import java.io.Serializable;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
import org.springframework.data.redis.serializer.JacksonJsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
public class Serializers {
record Product(String sku, BigDecimal price) implements Serializable {
}
record Basket(String owner) {
}
static void show(String label, RedisSerializer<Object> serializer, Object value) {
byte[] bytes = serializer.serialize(value);
String text = new String(bytes, StandardCharsets.ISO_8859_1);
boolean printable = text.chars().allMatch(c -> c >= 32 && c < 127);
System.out.println(label + " (" + serializer.getClass().getSimpleName() + "): "
+ bytes.length + " bytes");
System.out.println(" stored as: " + (printable ? text
: HexFormat.of().formatHex(bytes, 0, 16) + "... (binary)"));
System.out.println(" read back: " + serializer.deserialize(bytes));
}
public static void main(String[] args) {
Product product = new Product("book-42", new BigDecimal("12.50"));
show("java()", RedisSerializer.java(), product);
show("json()", RedisSerializer.json(), product);
JacksonJsonRedisSerializer<Product> typed = new JacksonJsonRedisSerializer<>(Product.class);
byte[] bytes = typed.serialize(product);
System.out.println("typed JSON (JacksonJsonRedisSerializer): " + bytes.length + " bytes");
System.out.println(" stored as: " + new String(bytes, StandardCharsets.UTF_8));
System.out.println(" read back: " + typed.deserialize(bytes));
byte[] key = RedisSerializer.string().serialize("product:book-42");
System.out.println("string() key: " + new String(key, StandardCharsets.UTF_8)
+ " (" + key.length + " bytes)");
try {
RedisSerializer.java().serialize(new Basket("ana"));
} catch (SerializationException e) {
System.out.println("java() on a class that is not Serializable: "
+ e.getClass().getSimpleName());
System.out.println(" " + e.getMessage());
}
}
}
java() (JdkSerializationRedisSerializer): 398 bytes
stored as: aced00057372001353657269616c697a... (binary)
read back: Product[sku=book-42, price=12.50]
json() (GenericJacksonJsonRedisSerializer): 87 bytes
stored as: {"@class":"Serializers$Product","sku":"book-42","price":["java.math.BigDecimal",12.50]}
read back: Product[sku=book-42, price=12.50]
typed JSON (JacksonJsonRedisSerializer): 31 bytes
stored as: {"sku":"book-42","price":12.50}
read back: Product[sku=book-42, price=12.50]
string() key: product:book-42 (15 bytes)
java() on a class that is not Serializable: SerializationException
Cannot serialize
, JDK serialization, wrote 398 bytes of binary that start withjava() , the Java serialization header. Only a Java program with the same class on its classpath can read it, and renaming or moving the class breaks every stored value.aced0005 wrote 87 bytes of JSON with anjson() property and the@class 's type next to its value. That type information lets it read any object back without being told the class, at the cost of tying the data to Java class names.BigDecimal for one type wrote 31 bytes, just the fields. It is the most compact and the easiest for other languages to read, but each serializer instance handles one type.JacksonJsonRedisSerializer stored the keystring() as its 15 UTF-8 bytes, readable as it is inproduct:book-42 .redis-cli refused a record that does not implementjava() with aSerializable .SerializationException
The trap is in the defaults. The auto-configured RedisTemplate<Object, Object>"product:book-42"StringRedisTemplateStringRedisTemplateRedisTemplatestring()
Spring Data Redis 4 uses Jackson 3 for JacksonJsonRedisSerializerGenericJacksonJsonRedisSerializerJackson2JsonRedisSerializerGenericJackson2JsonRedisSerializer
Redis as the Spring cache
With @EnableCachingRedisCacheManager@Cacheable
package demo.redis.cache;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HexFormat;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.cache.autoconfigure.RedisCacheManagerBuilderCustomizer;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair;
import org.springframework.data.redis.serializer.RedisSerializer;
public class CacheSetup {
@SpringBootApplication
@EnableCaching
static class ShopApplication {
// per-cache settings on top of the spring.cache.redis.* defaults
@Bean
RedisCacheManagerBuilderCustomizer perCacheTtl() {
return builder -> builder.withCacheConfiguration("prices",
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(30))
.serializeValuesWith(SerializationPair.fromSerializer(
RedisSerializer.json())));
}
}
static void describe(CacheManager manager, String name) {
RedisCacheConfiguration config = ((RedisCache) manager.getCache(name))
.getCacheConfiguration();
System.out.println("cache '" + name + "':");
System.out.println(" key for 42 : " + config.getKeyPrefixFor(name) + "42");
System.out.println(" time to live : "
+ config.getTtlFunction().getTimeToLive("42", "value"));
System.out.println(" caches nulls : " + config.getAllowCacheNullValues());
ByteBuffer written = config.getValueSerializationPair().write("hi");
byte[] bytes = new byte[written.remaining()];
written.get(bytes);
System.out.println(" \"hi\" is stored as: " + (bytes[0] == '"'
? new String(bytes, StandardCharsets.UTF_8) + " (JSON)"
: HexFormat.of().formatHex(bytes) + " (JDK serialization)"));
}
public static void main(String[] args) {
try (var context = SpringApplication.run(ShopApplication.class,
"--spring.main.banner-mode=off", "--logging.level.root=WARN",
"--spring.cache.cache-names=orders,prices",
"--spring.cache.redis.time-to-live=10m",
"--spring.cache.redis.key-prefix=shop:",
"--spring.cache.redis.cache-null-values=false")) {
CacheManager manager = context.getBean(CacheManager.class);
System.out.println("CacheManager: " + manager.getClass().getSimpleName());
describe(manager, "orders");
describe(manager, "prices");
}
}
}
CacheManager: RedisCacheManager
cache 'orders':
key for 42 : shop:orders::42
time to live : PT10M
caches nulls : false
"hi" is stored as: aced00057400026869 (JDK serialization)
cache 'prices':
key for 42 : prices::42
time to live : PT30S
caches nulls : true
"hi" is stored as: "hi" (JSON)
- The
cache took theorders properties. Entry 42 would be stored underspring.cache.redis.* : the key prefix, the cache name, two colons and the key. It expires after 10 minutes and never caches ashop:orders::42 result.null - Its values use JDK serialization:
became"hi" . That is the cache's default, the same as the template's.aced0005... - The
cache was configured by the customizer: 30 seconds and JSON, soprices was stored as"hi" ."hi" - But
also lost the property defaults: its key isprices with noprices::42 prefix, and it cachesshop: values again. A configuration built fromnull starts from the library defaults, not from Spring Boot's properties.RedisCacheConfiguration.defaultCacheConfig()
Always set a time to live. Without one, cached entries never expire, and the cache keeps stale data until it is evicted for memory. A shared prefix such as shop:@Cacheable@CachePut@CacheEvict
When Redis is down
A cache should make the application faster, not less available. By default, though, a failed cache read is an exception like any other. This program calls a cached method with no Redis server, once with the default error handler and once with a handler that treats a failed read as a miss:
package demo.redis.outage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.SimpleCacheErrorHandler;
import org.springframework.stereotype.Service;
public class CacheOutage {
@SpringBootApplication
@EnableCaching
static class ShopApplication implements CachingConfigurer {
static boolean tolerant;
@Override
public CacheErrorHandler errorHandler() {
if (!tolerant) {
return new SimpleCacheErrorHandler(); // the default: rethrow
}
return new SimpleCacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
System.out.println(" cache get failed for " + cache.getName() + "::" + key
+ " (" + e.getClass().getSimpleName() + "), calling the method");
}
};
}
}
@Service
static class PriceService {
@Cacheable("prices")
public String price(String sku) {
System.out.println(" loading the price of " + sku + " from the database");
return sku + " costs 12.50";
}
}
static void run(boolean tolerant) {
ShopApplication.tolerant = tolerant;
System.out.println(tolerant ? "Tolerant error handler:" : "Default error handler:");
try (var context = SpringApplication.run(ShopApplication.class,
"--spring.main.banner-mode=off", "--logging.level.root=OFF",
"--spring.data.redis.port=6390")) { // no Redis server on this port
PriceService prices = context.getBean(PriceService.class);
try {
System.out.println(" result: " + prices.price("book-42"));
} catch (RuntimeException e) {
System.out.println(" call failed: " + e.getClass().getSimpleName()
+ ": " + e.getMessage());
}
}
}
public static void main(String[] args) {
run(false);
run(true);
}
}
Default error handler:
call failed: RedisConnectionFailureException: Unable to connect to Redis
Tolerant error handler:
cache get failed for prices::book-42 (RedisConnectionFailureException), calling the method
loading the price of book-42 from the database
result: book-42 costs 12.50
- With the default
, the call failed withSimpleCacheErrorHandler . The price was available in the database all along, but the method never ran: a cache outage became an outage of every cached endpoint.RedisConnectionFailureException - With the overridden
, the failed read was reported and treated as a miss. The method loaded the price from the database, and the caller gothandleCacheGetError .book-42 costs 12.50
Register the handler by implementing CachingConfigurerhandleCachePutErrorhandleCacheEvictErrorhandleCacheClearError
Data structures with RedisTemplate (not run)
Beyond caching, Redis's data types solve common problems in one command each. StringRedisTemplateopsForValue()opsForHash()opsForList()opsForSet()opsForZSet()
@Service
public class ShopRedis {
private final StringRedisTemplate redis;
public ShopRedis(StringRedisTemplate redis) {
this.redis = redis;
}
// a value with a time to live: SET session:abc ... EX 1800
public void saveSession(String id, String json) {
redis.opsForValue().set("session:" + id, json, Duration.ofMinutes(30));
}
// an atomic counter: INCR, safe with many application instances
public long countView(String productId) {
return redis.opsForValue().increment("views:" + productId);
}
// a hash: one key with named fields, read or updated one field at a time
public void saveCart(String user, String sku, int quantity) {
redis.opsForHash().put("cart:" + user, sku, String.valueOf(quantity));
}
// a sorted set: members ordered by score, here a leaderboard
public Set<String> topSellers(int n) {
return redis.opsForZSet().reverseRange("sales:2026-11", 0, n - 1);
}
}
maps toincrement , which Redis runs atomically. Two application instances counting the same view can never lose an update, unlike a read, add and write in Java.INCR- A hash is the right shape for an object whose fields change separately, such as a cart; updating one item does not rewrite the rest.
- Name keys with a type and an id separated by colons, such as
. Tools group keys by those segments, and a consistent scheme makes them easy to find withcart:ana .SCAN - Never call
in production code.keys("*") walks every key while blocking the single command thread;KEYS walks them in small batches.redis.scan(ScanOptions.scanOptions().match("cart:*").build())
Locks, transactions and scripts (not run)
A short lock that several application instances respect is built from one atomic command: set the key only if it does not exist, with an expiry so that a crashed holder cannot keep it forever:
public boolean runOnce(String job, Runnable task) {
String token = UUID.randomUUID().toString();
Boolean acquired = redis.opsForValue()
.setIfAbsent("lock:" + job, token, Duration.ofSeconds(30)); // SET NX EX
if (!Boolean.TRUE.equals(acquired)) {
return false; // another instance holds the lock
}
try {
task.run();
return true;
} finally {
// delete only our own lock: compare and delete in one atomic Lua script
redis.execute(RedisScript.of("""
if redis.call('get', KEYS[1]) == ARGV[1]
then return redis.call('del', KEYS[1]) else return 0 end""", Long.class),
List.of("lock:" + job), token);
}
}
- The random token matters. If the task outlives the 30 seconds, another instance may take the lock, and a plain
would then remove that instance's lock. The script deletes only when the stored token is still ours.delete - Such a lock is fine for avoiding duplicate work, such as a scheduled job on several instances. It is not safe for correctness under failover, because a Redis replica can lose a recent write. For that, use a database lock, or ShedLock for scheduled jobs.
- Redis transactions,
andMULTI , are available throughEXEC . They queue commands and run them together, but there is no rollback, and a value cannot be read in the middle of one. A Lua script is usually the simpler way to make several steps atomic.redis.execute(SessionCallback) - Pipelining, with
, sends many commands without waiting for each reply, which cuts network round trips when loading thousands of keys.redis.executePipelined(...)
Pub/sub and repositories (not run)
Redis can also deliver messages. A publisher calls convertAndSend
@Bean
RedisMessageListenerContainer listeners(RedisConnectionFactory factory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(factory);
container.addMessageListener(
(message, pattern) -> System.out.println("price changed: " + message),
new ChannelTopic("price-changes"));
return container;
}
// elsewhere: redis.convertAndSend("price-changes", "book-42");
Pub/sub keeps nothing: a subscriber that is down misses the message. That suits cache invalidation across instances, where a missed message only means a stale entry until its time to live runs out. For messages that must not be lost, use Redis Streams through StreamMessageListenerContainer
Spring Data repositories also work on Redis. An entity annotated with @RedisHash("carts")@Id@IndexedfindBy...@TimeToLive
Running Redis in production
- Memory limits: set
and an eviction policy on the server. For a pure cache,maxmemory evicts the least recently used keys; the default,allkeys-lru , makes writes fail when memory is full.noeviction - Timeouts: set
andspring.data.redis.timeout to values that match a cache, such as a few hundred milliseconds, not the client's 60-second default.spring.data.redis.connect-timeout - Big keys: a hash or list with millions of entries blocks the server while it is read or deleted. Split large structures, and delete big keys with
, which frees memory in the background.UNLINK - Health checks: with Actuator, Spring Boot adds a Redis health indicator. Do not add it to the readiness group if the application can run without its cache, or a Redis outage takes every instance out of the load balancer.
- Tests: run integration tests against a real Redis in a container with
, as the@ServiceConnectionTestcontainers page shows.
Choosing the right Redis feature
| Need | Feature |
|---|---|
| Cache method results | @CacheableRedisCacheManagerCacheErrorHandler |
| Strings, counters and values with an expiry | StringRedisTemplate.opsForValue() |
| Objects whose fields change separately | opsForHash() |
| Rankings and time-ordered data | opsForZSet() |
| Avoid duplicate work across instances | setIfAbsent |
| Several steps that must be atomic | A Lua script with RedisScript |
| Notify all instances, losing messages is acceptable | Pub/sub with RedisMessageListenerContainer |
| Messages that must not be lost | Redis Streams, or a broker |
| Values readable by other languages | string()JacksonJsonRedisSerializer |
Start with StringRedisTemplate