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

在Spring Boot中集成Redis进行缓存

在Spring Boot中集成Redis进行缓存,主要分为以下步骤:


1. 添加依赖

pom.xml中添加Redis和缓存相关的依赖:

<!-- Spring Boot Redis Starter -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency><!-- 可选:对象序列化支持(如Jackson) -->
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId>
</dependency>

2. 配置Redis连接

application.propertiesapplication.yml中配置Redis服务器信息:

# Redis基础配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=  # 若无密码则留空
spring.redis.database=0# 连接池配置(可选)
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0

3. 启用缓存功能

在启动类上添加@EnableCaching注解:

@SpringBootApplication
@EnableCaching // 启用缓存
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}

4. 配置缓存管理器(可选但推荐)

自定义Redis缓存配置(如设置过期时间、序列化方式):

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;@Configuration
@EnableCaching
public class RedisCacheConfig {@Beanpublic RedisCacheConfiguration cacheConfiguration() {return RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10)) // 默认缓存过期时间:10分钟.disableCachingNullValues() // 不缓存null值.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer() // 使用JSON序列化));}
}

5. 在Service层使用缓存注解

在需要缓存的方法上添加Spring Cache注解:

注解作用
@Cacheable查询时优先读缓存,无缓存则执行方法并保存结果
@CachePut每次执行方法并更新缓存(常用于更新操作)
@CacheEvict删除缓存(常用于删除或更新操作)

示例代码:

@Service
public class UserService {// 根据ID查询用户(结果缓存到"users"区域,key为#id)@Cacheable(value = "users", key = "#id")public User getUserById(Long id) {// 模拟数据库查询return userRepository.findById(id).orElse(null);}// 更新用户信息(同时更新缓存)@CachePut(value = "users", key = "#user.id")public User updateUser(User user) {return userRepository.save(user);}// 删除用户(同时移除缓存)@CacheEvict(value = "users", key = "#id")public void deleteUser(Long id) {userRepository.deleteById(id);}// 清除"users"区域所有缓存(如批量更新后)@CacheEvict(value = "users", allEntries = true)public void clearAllUserCache() {}
}

6. 验证缓存效果

  • 观察日志:首次查询会访问数据库,后续相同请求不会打印SQL。
  • Redis命令行检查
    redis-cli
    > KEYS *      # 查看所有缓存键
    > GET "users::1"  # 查看key为1的用户缓存
    
  • 强制刷新缓存:更新数据后,检查缓存是否被清除/更新。

常见问题解决

  1. 序列化异常

    • 确保实体类实现java.io.Serializable接口。
    • 使用JSON序列化(如GenericJackson2JsonRedisSerializer)。
  2. 缓存穿透

    • 对空结果也进行短时间缓存(需自定义配置)。
    • 使用@Cacheableunless参数:
      @Cacheable(value="users", unless="#result == null")
      
  3. 缓存一致性

    • 更新数据库后立即清除或更新缓存(通过@CachePut/@CacheEvict)。

通过以上步骤,即可在Spring Boot中高效集成Redis实现缓存功能,显著提升应用性能。

相关文章:

  • Linux.docker.k8s基础概念
  • 设计模式——建造者设计模式(创建型)
  • Windows上用FFmpeg采集摄像头推流 → MediaMTX服务器转发流 → WSL2上拉流播放
  • Visual Studio笔记:MSVC工具集、MSBuild
  • C++ 17 正则表达式
  • 机器学习与深度学习06-决策树02
  • day17 常见聚类算法
  • 深入理解MCP模型协议:构建全能AI服务端
  • 学习STC51单片机22(芯片为STC89C52RCRC)
  • LLMTIME: 不用微调!如何用大模型玩转时间序列预测?
  • Pytorch---ImageFolder
  • 什么是闭包
  • 姜老师MBTI课程:ISTP和ISFP
  • Thinkphp6实现websocket
  • 秒杀系统—5.第二版升级优化的技术文档三
  • 设备健康管理的战略升维:用预测性维护重构企业竞争力
  • Linux 基础IO(上)
  • VR/AR 显示瓶颈将破!铁电液晶技术迎来关键突破
  • Android15 userdebug版本不能remount
  • 玩客云 OEC/OECT 笔记
  • 青岛网站优化/宁波seo推广平台
  • 益阳网站建设/推广普通话手抄报
  • 陕西网站建设设计公司/北京seo报价
  • 医院网站建设的特点/推广产品的软文怎么写
  • 微网站建设比较全面的是/新闻软文自助发布平台
  • 做网站资金来源是什么/海口seo快速排名优化