🎬 HoRain 云小助手个人主页

⛺️生活的理想,就是为了理想的生活!


⛳️ 推荐

前些天发现了一个超棒的服务器购买网站,性价比超高,大内存超划算!忍不住分享一下给大家。点击跳转到网站。

目录

⛳️ 推荐

Spring Cache与Redis结合基本使用指南

1. 添加依赖

2. 配置Redis连接

3. 启用缓存

4. 使用缓存注解

@Cacheable - 缓存读取

@CachePut - 缓存更新

@CacheEvict - 缓存删除

5. 自定义缓存配置(JSON序列化)

6. 实际使用示例

7. 缓存操作说明

8. 最佳实践建议


Spring Cache与Redis结合基本使用指南

根据知识库信息,我为您整理了Spring Cache与Redis结合的基本使用方法:

1. 添加依赖

pom.xml中添加以下依赖:

<!-- Redis依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- Spring Cache依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

2. 配置Redis连接

application.properties中配置:

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=yourpassword

或在application.yml中配置:

spring:
  redis:
    host: 192.168.1.100
    port: 6379
    password: 密码
    database: 0
    timeout: 10000ms
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: -1ms

3. 启用缓存

在主配置类上添加@EnableCaching注解:

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

4. 使用缓存注解

@Cacheable - 缓存读取

@Service
public class ProductService {
    @Cacheable(value = "products", key = "#id")
    public Product getProductById(Long id) {
        System.out.println("Fetching product from the database for id: " + id);
        return new Product(id, "Product " + id, 100.0);
    }
}

@CachePut - 缓存更新

@CachePut(value = "products", key = "#product.id")
public Product updateProduct(Product product) {
    // 更新产品信息
    return product;
}

@CacheEvict - 缓存删除

@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
    // 删除产品
}

5. 自定义缓存配置(JSON序列化)

默认情况下,Redis存储的是Java序列化字节流,建议配置为JSON格式:

@Configuration
@EnableCaching
public class RedisCacheConfig {
    
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
            // 设置key为String序列化
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
            // 设置value为JSON序列化
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
            // 不缓存null值
            .disableCachingNullValues()
            // 默认缓存1小时
            .entryTtl(Duration.ofHours(1));
        
        return RedisCacheManager.builder(factory)
            .cacheDefaults(config)
            .build();
    }
}

6. 实际使用示例

创建REST控制器访问缓存数据:

@RestController
public class ProductController {
    
    @Autowired
    private ProductService productService;
    
    @GetMapping("/product/{id}")
    public Product getProduct(@PathVariable Long id) {
        return productService.getProductById(id);
    }
}

7. 缓存操作说明

操作 描述
缓存读取 使用@Cacheable,方法调用时先检查缓存,命中则直接返回
缓存更新 使用@CachePut,强制将方法返回结果更新到缓存
缓存删除 使用@CacheEvict,从缓存中移除指定条目
缓存存储 Redis将数据以键值对形式存储在内存中,可设置TTL

8. 最佳实践建议

  1. 序列化选择:避免使用JDK序列化,推荐使用JSON序列化(如GenericJackson2JsonRedisSerializer
  2. 连接池配置:生产环境必须配置Lettuce连接池限制,避免资源耗尽
  3. TTL设置:根据业务需求合理设置缓存过期时间
  4. 空值缓存:考虑缓存空值,防止缓存穿透
  5. 缓存粒度:根据查询模式选择合适的缓存粒度(整个对象或部分字段)

通过Spring Cache与Redis的结合使用,可以大幅提高应用性能,减少数据库访问次数,同时确保缓存数据的一致性和及时更新。

❤️❤️❤️本人水平有限,如有纰漏,欢迎各位大佬评论批评指正!😄😄😄

💘💘💘如果觉得这篇文对你有帮助的话,也请给个点赞、收藏下吧,非常感谢!👍 👍 👍

🔥🔥🔥Stay Hungry Stay Foolish 道阻且长,行则将至,让我们一起加油吧!🌙🌙🌙

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐