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

发布于:2025-06-11 ⋅ 阅读:(42) ⋅ 点赞:(0)

一、基础配置步骤

1. 添加依赖

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

<!-- 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格式配置文件中配置如下:
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(可选)
如果需要自定义序列化方式,可以创建配置类: 

@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注解:

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

直接使用RedisTemplate

注入RedisTemplate进行操作:

@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);
}

二、使用缓存注解

常用注解示例:
@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配置:

@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序列化

网站公告

今日签到

点亮在社区的每一天
去签到