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序列化
相关推荐
闫小生5 分钟前
解决IntelliJ IDEA配置文件application.properties乱码的问题
java·spring boot·intellij-idea
苏格拉没有底_coder10 分钟前
Redis+Kafka实现动态延时任务
数据库·redis·kafka
汪小白JIY1 小时前
【C#】多级缓存与多核CPU
缓存·c#·多级缓存
程序员阿超的博客1 小时前
云原生核心技术 (10/12): K8s 终极实战:从零部署一个 Spring Boot + MySQL + Redis 应用
spring boot·云原生·kubernetes
qq_12498707531 小时前
基于Node.js的线上教学系统的设计与实现(源码+论文+调试+安装+售后)
java·spring boot·后端·node.js·毕业设计
seventeennnnn2 小时前
Java面试实战:Spring Boot+微服务+AI的谢飞机闯关之路 | CSDN博客精选
spring boot·redis·spring cloud·微服务·ai·java面试·rag
Zfox_3 小时前
Redis:渐进式遍历
服务器·数据库·redis·缓存
bing_1583 小时前
Spring Boot 项目中Http 请求如何对响应体进行压缩
spring boot·后端·http
无名之逆4 小时前
Junior Year Self-Study Notes My Journey with the Hyperlane Framework
java·开发语言·前端·spring boot·后端·rust·编程
crud4 小时前
Spring Boot 整合 Smart-Doc:零注解生成 API 文档,告别 Swagger
java·spring boot·swagger