Redis
Table of Contents
Using redis for caching
See
- https://github.com/explorer436/programming-playground/tree/main/java-playground/redis-caching-using-lettuce
- https://github.com/explorer436/programming-playground/tree/main/java-playground/redis-cacing-using-jedis
Using it for caching results from the DAO layer
This can reduce database loads drastically (by 70%) for read-heavy operations.
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.disableCachingNullValues();
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(cacheConfig)
.withCacheConfiguration("products",
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(5)))
.withCacheConfiguration("categories",
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1)))
.build();
}
}
And then using it
@Service
public class ProductService {
// Other code
@Cacheable(value = "products", key = "#id")
public Mono<Product> getProductById(Long id) {
return repository.findById(id)
.switchIfEmpty(Mono.error(new ProductNotFoundException(id)));
}
@CacheEvict(value = "products", key = "#product.id")
public Mono<Product> updateProduct(Product product) {
return repository.save(product);
}
}
What can you use Redis for other than caching?
Redis is an open-source, in-memory data structure store that can function as a database, cache, and message broker.
Most engineers think of Redis just for caching, but it’s far more versatile. Here are some powerful use cases you might not know:
- Distributed Locks
- Use Case: Ensuring exclusive access to shared resources in distributed systems.
- Example: Preventing multiple servers from modifying the same record at the same time, ensuring data consistency.
- Real-time Counters
- Use Case: Tracking event occurrences in real-time.
- Example: Monitoring active users on a website or counting how many times a button is clicked.
- Rate Limiting
- Use Case: Controlling how many times an action can be performed within a time window.
- Example: Throttling API requests to prevent abuse and protect backend servers.
- Leaderboards & Rankings
- Use Case: Managing dynamic, real-time rankings based on scores or metrics.
- Example: Displaying the top players in a game or ranking top products based on user ratings.
- Session Storage
- Use Case: Maintaining user session data efficiently.
- Example: Keeping users logged in across multiple requests without hitting the database frequently.
- Message Queues
- Use Case: Enabling asynchronous communication between services.
- Example: Background job processing—offloading tasks like email notifications or data processing.
- Inventory Management
- Use Case: Keeping track of stock levels in real-time.
- Example: Ensuring accurate stock updates in an e-commerce store to prevent overselling.