SpringBoot项目使用Redis作为数据缓存

一、基础配置步骤

1. 添加依赖

pom.xml中引入Redis和Cache依赖:

XML 复制代码
<!-- Redis Starter -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- Spring Cache Abstraction -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2. 配置Redis连接,YAML格式配置文件中配置如下:
XML 复制代码
spring:
  redis:
    host: 127.0.0.1      # Redis服务器IP地址(默认本地)
    port: 6379           # Redis服务端口(默认6379)
    password:            # 访问密码(没有密码则留空)
    database: 0          # 使用的Redis数据库索引(0-15)
    jedis:               # Jedis连接池配置
      pool:
        max-active: 8    # 连接池最大活跃连接数(默认8)
        max-wait: -1ms   # 获取连接最大等待时间(-1表示无限等待)
        max-idle: 8      # 连接池最大空闲连接数(建议与max-active相同)
        min-idle: 0      # 连接池最小空闲连接数(默认0)

关键参数说明:

  1. max-activemax-idle 建议设为相同值,避免频繁创建/销毁连接
  2. max-wait: -1ms 表示如果没有可用连接会一直阻塞等待
  3. database 可指定0-15之间的值,不同业务建议使用不同库隔离数据

‌3.配置RedisTemplate(可选)

如果需要自定义序列化方式,可以创建配置类:

java 复制代码
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(RedisSerializer.string());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
}
4. 启用缓存功能

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

java 复制代码
@SpringBootApplication
@EnableCaching  // 关键注解:启用缓存
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

直接使用RedisTemplate

注入RedisTemplate进行操作:

java 复制代码
@Autowired
private RedisTemplate<String, Object> redisTemplate;

public void setValue(String key, Object value) {
    redisTemplate.opsForValue().set(key, value);
}

public Object getValue(String key) {
    return redisTemplate.opsForValue().get(key);
}

二、使用缓存注解

常用注解示例:
java 复制代码
@Service
public class ProductService {

    // 缓存结果,若缓存存在则直接返回
    @Cacheable(value = "products", key = "#id")
    public Product getProductById(Long id) {
        // 模拟数据库查询
        return productRepository.findById(id).orElse(null);
    }

    // 更新缓存
    @CachePut(value = "products", key = "#product.id")
    public Product updateProduct(Product product) {
        return productRepository.save(product);
    }

    // 删除缓存
    @CacheEvict(value = "products", key = "#id")
    public void deleteProduct(Long id) {
        productRepository.deleteById(id);
    }
}
注解说明:
注解 作用
@Cacheable 方法结果缓存,若缓存命中则直接返回结果,不执行方法体
@CachePut 强制更新缓存(始终执行方法体,并将结果存入缓存)
@CacheEvict 删除指定缓存
@Caching 组合多个缓存操作

三、高级配置(可选)

通过RedisCacheManager配置:

java 复制代码
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
        .entryTtl(Duration.ofMinutes(30));  // 设置全局默认过期时间30分钟

    return RedisCacheManager.builder(factory)
            .cacheDefaults(config)
            .build();
}

四、常见问题解决

  1. 缓存不生效 ‌:
    • 检查是否漏加@EnableCaching
    • 确认方法调用来自外部类(同类内调用因代理问题不生效)
  2. 序列化错误 ‌:
    • 默认使用JDK序列化,建议配置JSON序列化
相关推荐
ladymorgana26 分钟前
【Spring boot】tomcat Jetty Undertow对比,以及应用场景
spring boot·tomcat·jetty
IT_102429 分钟前
Spring Boot项目开发实战销售管理系统——系统设计!
大数据·spring boot·后端
DCTANT1 小时前
【原创】国产化适配-全量迁移MySQL数据到OpenGauss数据库
java·数据库·spring boot·mysql·opengauss
Touper.2 小时前
SpringBoot -- 自动配置原理
java·spring boot·后端
喜欢敲代码的程序员3 小时前
SpringBoot+Mybatis+MySQL+Vue+ElementUI前后端分离版:项目搭建(一)
spring boot·mysql·elementui·vue·mybatis
weixin_438335404 小时前
分布式锁实现方式:基于Redis的分布式锁实现(Spring Boot + Redis)
数据库·redis·分布式
华子w9089258594 小时前
基于 SpringBoot+Vue.js+ElementUI 的 “花开富贵“ 花园管理系统设计与实现7000字论文
vue.js·spring boot·elementui
暮乘白帝过重山4 小时前
为什么要写RedisUtil这个类
redis·开发·暮乘白帝过重山
数据狐(DataFox)5 小时前
SQL参数化查询:防注入与计划缓存的双重优势
数据库·sql·缓存
小时候的阳光5 小时前
SpringBoot3 spring.factories 自动配置功能不生效?
spring boot·spring·失效·factories·imports