How to Implement Redis Cache Preheating in Spring
This article explains the concept of cache preheating, provides an abstract cache class, a Spring context utility, and a CommandLineRunner implementation that automatically loads hot data into Redis at startup, demonstrating the approach with a news‑cache example and related controller code.
Cache Preheating
Cache preheating loads hot data into a cache (e.g., Redis) during application startup or after cache expiration, so subsequent requests find the data already cached, reducing cache penetration, cache breakdown, and load on the database.
Abstract Cache Class
public abstract class AbstractCache {
/** Initialize cache */
protected abstract void init();
/** Retrieve cached value */
public abstract <T> T get();
/** Clear cache */
public abstract void clear();
/** Reload cache */
public void reload() {
clear();
init();
}
}Spring ApplicationContext Utility
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
ApplicationContextUtil.applicationContext = ctx;
}
/** Obtain the Spring context */
public static ApplicationContext getContext() {
return applicationContext;
}
}Cache Preheat Handler (CommandLineRunner)
@Component
@ConditionalOnProperty(name = {"cache.init.enable"}, havingValue = "true", matchIfMissing = false)
public class CachePreheatHandler implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
ApplicationContext ctx = ApplicationContextUtil.getContext();
java.util.Map<String, AbstractCache> beans = ctx.getBeansOfType(AbstractCache.class);
for (java.util.Map.Entry<String, AbstractCache> entry : beans.entrySet()) {
AbstractCache cache = ctx.getBean(entry.getValue().getClass());
cache.init();
}
}
}The handler executes only when the configuration property cache.init.enable is set to true (default false).
cache.init.enable=trueExample: News Cache
@Component
@RequiredArgsConstructor
public class NewsCache extends AbstractCache {
private static final String NEWS_KEY = "news";
private final RedisTemplate<String, Object> redisTemplate;
private final NewsService newsService;
@Override
protected void init() {
if (Boolean.FALSE.equals(redisTemplate.hasKey(NEWS_KEY))) {
redisTemplate.opsForValue().set(NEWS_KEY, newsService.list(), 30, TimeUnit.MINUTES);
}
}
@Override
public <T> T get() {
if (Boolean.FALSE.equals(redisTemplate.hasKey(NEWS_KEY))) {
reload();
}
return (T) redisTemplate.opsForValue().get(NEWS_KEY);
}
@Override
public void clear() {
redisTemplate.delete(NEWS_KEY);
}
}When the application starts, NewsCache.init() stores the hot news list in Redis under the key news with a 30‑minute TTL.
Controller Accessing the Cache
@RestController
@RequestMapping("/news")
@RequiredArgsConstructor
public class NewsController {
private final NewsCache newsCache;
@GetMapping("/cache")
public java.util.List<News> list() {
return newsCache.get();
}
}After startup, a request to /news/cache returns the pre‑loaded news data directly from Redis without triggering a database query.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
