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-active 和 max-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序列化
相关推荐
小蒜学长1 天前
基于Spring Boot+Vue3的在线医疗咨询系统的设计与实现(代码+数据库+LW)
java·spring boot·后端·在线问诊·在线医疗咨询系统
夕除1 天前
redis--模型
redis
m0_639906941 天前
SpringBoot自动配置原理
java·spring boot·后端
John_Hui1 天前
第 5 篇:Ubuntu 安装 Redis
数据库·redis·缓存
Navicat中国1 天前
Navicat 连接 Redis 数据库
数据库·redis·数据库开发·navicat
aiks_yuan1 天前
Spring AI MCP Server 怎么接入 Claude Code:Spring Boot 用 @McpTool 暴露接口(Spring AI 2.0.2 实测)
spring boot
l1t1 天前
DeepSeek总结的ALTER FUNCTION SET work_mem:无需全局更改即可修复 PostgreSQL 磁盘溢出
sql·缓存·postgresql
学长毕设1 天前
基于springboot的实验室设备管理系统
java·spring boot·后端
学长毕设1 天前
基于springboot的社区养老监护系统的设计与实现
java·spring boot·后端