Skip to main content
Advertisement

13.1 Redis-Based Global Caching and Distributed Session Sharing

Redis transcends being a simple in-memory database — it is the foundational distributed systems infrastructure for synchronizing shared state (cache, sessions, locks) across multiple server instances.

1. Spring Cache Abstraction (@Cacheable) with Redis

Spring's caching abstraction uses @Cacheable, @CacheEvict, and @CachePut annotations to automatically store and retrieve method results from Redis, completely decoupling this logic from your business code.

implementation 'org.springframework.boot:spring-boot-starter-data-redis'
spring:
data:
redis:
host: localhost
port: 6379
# password: Always set in production environments
@Configuration
@EnableCaching // Activates all cache annotation functionality
public class CacheConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(30)) // 30-minute cache TTL
.disableCachingNullValues() // Don't cache null values
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
}
}
@Service
@RequiredArgsConstructor
public class ProductService {
private final ProductRepository productRepository;

// Returns cached result from Redis if available — skips DB query entirely
@Cacheable(value = "products", key = "#productId")
public ProductDto getProduct(Long productId) {
return productRepository.findById(productId)
.map(ProductDto::from)
.orElseThrow(() -> new NotFoundException("Product not found."));
}

// Evicts the cache on update so next read fetches fresh data from DB
@CacheEvict(value = "products", key = "#productId")
public void updateProduct(Long productId, ProductUpdateDto dto) {
// ...update logic
}
}

2. Distributing HttpSession via Redis (Spring Session)

In a scale-out environment, server instance A cannot read sessions created by instance B. With Spring Session, you can switch the session store to Redis without changing a single line of existing HttpSession code.

implementation 'org.springframework.session:spring-session-data-redis'
spring:
session:
store-type: redis
timeout: 30m

With this single configuration, all session R/W via request.getSession() routes to Redis instead of local WAS memory — enabling seamless session sharing across any number of servers behind a load balancer.

Advertisement