当前位置: 首页 > news >正文

基于 SpringBoot 与 Redis 的缓存预热案例

文章目录

    • “缓存预热” 是什么?
    • 项目环境搭建
    • 创建数据访问层
    • 预热数据到 Redis 中
    • 创建缓存服务类
    • 测试缓存预热

“缓存预热” 是什么?

缓存预热是一种优化策略,在系统启动或者流量高峰来临之前,将一些经常访问的数据提前加载到缓存中。这样做的好处是,当用户实际请求这些数据时,能够直接从缓存中获取,避免了从数据库等慢速数据源中查询数据,从而提高系统的响应速度和吞吐量,减少数据库的压力。

缓存预热通常发生在以下情况下:

  1. 系统投入使用前:

    在系统正式投入使用之前,可以对一些初始化数据进行预热,以避免系统上线初期因为大量数据未被缓存而导致的性能问题。

  2. 数据访问热度周期性变化较高的情况下:

    对于有些数据,其访问热度可能会随着时间变化而变化,可以在预计到达高峰期之前预热这些数据,以确保在高峰期能够直接从缓存中获取,提高系统性能。

实际上,缓存预热是一种以时间换空间的策略,通过预先将需要频繁访问的数据加载到缓存中,来减少后续访问时因为缓存未命中而导致的性能损失。

例如,一个电商网站准备举办大型促销活动,预计将有大量用户访问某一特定类别的商品页面。为了避免在活动期间因为商品数据缓存未命中而导致系统性能下降,可以提前对这一类别的商品信息进行缓存预热。即在活动开始之前,系统可以将这类商品的信息提前加载到缓存中,以确保在活动期间可以直接从缓存中获取数据,提高系统的响应速度。

以下是一个基于 SpringBoot 与 Redis 的缓存预热案例。

项目环境搭建

  • 引入依赖:

    <dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId>
    </dependency>
    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId>
    </dependency>
    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
  • 定义启动类:

    package test;import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
    public class SpringBootApp {public static void main(String[] args) {SpringApplication.run(SpringBootApp.class, args);}}
    
  • 定义配置:

    spring:redis:# Redis主机IPhost: localhost# Redis主机端口port: 6379# Redis主机密码password:# 使用Redis的8号库database: 8# 使用lettuce客户端lettuce:# 连接池配置pool:# 最大连接数max-active: 8# 最大空闲连接max-idle: 8# 最小空闲连接min-idle: 0# 连接等待时间max-wait: 100
    

创建数据访问层

模拟从数据库中获取用户数据。

package test;import org.springframework.stereotype.Repository;import java.util.ArrayList;
import java.util.List;@Repository
public class UserDao {/*** 模拟从数据库中获取所有用户** @return 所有用户*/public List<User> getAllUsers() {List<User> users = new ArrayList<>();users.add(new User(1L, "Alice"));users.add(new User(2L, "Bob"));users.add(new User(3L, "Charlie"));return users;}}

预热数据到 Redis 中

实现 CommandLineRunner 接口,在 Spring Boot 应用启动时执行缓存预热操作。

package test;import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;import java.util.List;@Component
@Slf4j
public class CachePreheater implements CommandLineRunner {@Autowiredprivate UserDao userDao;@Autowiredprivate UserCacheService userCacheService;@Overridepublic void run(String... args) {// 从数据库获取所有用户数据List<User> users = userDao.getAllUsers();// 将用户数据缓存到 Redis 中userCacheService.cacheUsers(users);log.info("Cache preheating completed.");}}

启动 SpringBoot 应用,控制台输出如下结果:

在这里插入图片描述

以上结果说明,数据已经成功被预热到缓存(Redis)中。

创建缓存服务类

负责将用户数据缓存到 Redis 中,并从 Redis 中获取用户数据。

package test;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.List;@Service
public class UserCacheService {@Resourceprivate RedisTemplate<String, User> redisTemplate;public void cacheUsers(List<User> users) {for (User user : users) {redisTemplate.opsForValue().set("user:" + user.getId(), user);}}public User getUserFromCache(Long userId) {return redisTemplate.opsForValue().get("user:" + userId);}}

测试缓存预热

创建一个控制器来测试缓存是否预热成功。

package test;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;@RestController
public class UserController {@Autowiredprivate UserCacheService userCacheService;@GetMapping("/users/{userId}")public User getUser(@PathVariable Long userId) {return userCacheService.getUserFromCache(userId);}}

在浏览器中访问 http://localhost:8080/users/1,得到的响应结果:

在这里插入图片描述

以上结果说明,成功从缓存中获取到了预热到的数据。

相关文章:

  • git提交规范记录,常见的提交类型及模板、示例
  • Awesome-Embodied-AI:具身AI机器人领域最全资源汇总(含人形机器人,多足机器人,灵巧手等精选资源)
  • Java程序员转人工智能入门学习路线图(2025版)
  • 【速写】conda安装(linux)
  • android ams调试指令介绍
  • 深度学习实验中,需要设置验证集吗?
  • 【计算机视觉】CV实战项目-高分辨率遥感图像语义分割:High-Resolution-Remote-Sensing-Semantic-Segmentation
  • Zookeeper断开连接时分布式锁释放问题的解决方案
  • 线上查询车辆出险记录:快速掌握事故情况!
  • spring-rabbit的CachingConnectionFactory默认参数导致消费者Channel数量暴增问题解决
  • Linux学习——FTP(功能实现)
  • 【KWDB 创作者计划】_KWDB引领数据库技术革新的璀璨之星
  • 《Vue3学习手记6》
  • 【vLLM 学习】CPU 离线处理
  • Alibaba Druid 完整配置与 Keepalive 优化指南
  • 《全球反空间能力》报告翻译——部分1
  • Mysql中隐式内连接和显式内连接的区别
  • 自然语言to SQL的评估
  • 二叉树遍历(C语言版)
  • 小白学习python第四天
  • 俄乌战火不熄,特朗普在梵蒂冈与泽连斯基会晤后口风突变
  • 十四届全国人大常委会第十五次会议继续审议民营经济促进法草案
  • 普京发表声明感谢协助俄军收复库尔斯克州的朝鲜军人
  • 加拿大今日大选:房价、印度移民和特朗普,年轻人在焦虑什么?
  • 四川落马厅官周海琦受审,1000余人接受警示教育
  • 知名计算机专家、浙江大学教授张森逝世