Spring @Cacheable缓存注解用法说明

注解Cacheable 是 Spring 框架中用于缓存数据的方法或类的注解。通过使用这个注解,你可以避免重复计算和重复获取数据,从而提高应用程序的性能。

基本用法

  • 引入依赖

确保在你的项目中引入了 Spring Cache 相关的依赖。如果你使用的是 Spring Boot,可以在 pom.xml 中添加以下依赖:

html 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
  • 启用缓存

在主类或配置类上使用 @EnableCaching 注解来启用缓存功能。

java 复制代码
@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  • 使用 @Cacheable 注解

在需要缓存的方法上使用 @Cacheable 注解。

bash 复制代码
@Service
public class UserService {

    @Cacheable("lizz:users")
    public User getUserById(Long id) {
        // 模拟一个耗时的数据库查询
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new User(id, "John Doe");
    }
}
  • 配置缓存

Spring 提供了多种缓存实现,包括内存缓存(如 ConcurrentMapCache)、第三方缓存(如 EhCache、Caffeine、Redis 等)。可以在配置文件(如 application.propertiesapplication.yml)中进行配置。

  • 使用 ConcurrentMapCache本地缓存
bash 复制代码
spring:
  cache:
    type: simple
  • 使用 Redis 作为缓存
bash 复制代码
spring:
  cache:
    type: redis
  redis:
    host: 172.1.1.11
    port: 6379

高级用法

  • 缓存条件: condition

使用 condition 属性指定缓存条件,只换成id大于10的数据缓存

java 复制代码
@Cacheable(value = "lizz:users", condition = "#id > 10")
public User getUserById(Long id) {
    // ...
}
  • 自定义缓存键

使用 key 属性自定义缓存键。

java 复制代码
@Cacheable(value = "users", key = "#root.methodName + #id")
public User getUserById(Long id) {
    // ...
}
  • **同步更新:**sync

sync=true时,如果多个线程同时访问缓存中没有的数据,只有一个线程会执行方法以加载数据,其他线程会等待加载完成并获取相同的结果。这可以防止缓存穿透(即多个线程同时访问缓存时都绕过缓存直接访问底层存储)。

java 复制代码
@Cacheable(value = "users", sync = true)
public User getUserById(Long id) {
    // ...
}

缓存失效:@CacheEvict

  • allEntries=true:清除所有缓存数据
java 复制代码
@CacheEvict(value = "lizz:users", allEntries = true)
public void clearCache() {
    // //清除全部缓存相关的其他业务操作
}
  • key = "#id" :清除缓存集合中指定key的数据
java 复制代码
@CacheEvict(value = "lizz:users", key = "#id")
public void delUser(Long id) {
    //清除id缓存相关的其他业务操作
}
  • 缓存同步: @CachePut

使用 @CachePut 注解更新缓存。

java 复制代码
@CachePut(value = "lizz:users", key = "#user.id")
public User updateUser(User user) {
    // 更新用户的逻辑
    return user;
}

结合缓存组件

  • 引入caffeine
html 复制代码
        <!--快速本地缓存-->
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
        </dependency>
  • 使用caffeine作为springcache管理
java 复制代码
@EnableCaching
@Configuration
public class CaffeineCacheConfig {

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager("ta:region");
        cacheManager.setCaffeine(caffeineCacheBuilder());
        return cacheManager;
    }

    Caffeine<Object, Object> caffeineCacheBuilder() {
        return Caffeine.newBuilder()
                .expireAfterWrite(1, TimeUnit.MINUTES)
                .maximumSize(100);
    }
}
相关推荐
失散1314 分钟前
分布式专题——10.4 ShardingSphere-Proxy服务端分库分表
java·分布式·架构·shardingsphere·分库分表
Bellafu6662 小时前
spring项目部署后为什么会生成 logback-spring.xml文件
java
递归不收敛2 小时前
一、Java 基础入门:从 0 到 1 认识 Java(详细笔记)
java·开发语言·笔记
沐浴露z2 小时前
【Java SpringAI智能体开发学习 | 2】SpringAI 实用特性:自定义Advisor,结构化输出,对话记忆持久化,prompt模板,多模态
java·spring·springai
小沈同学呀2 小时前
创建一个Spring Boot Starter风格的Basic认证SDK
java·spring boot·后端
码农小伙3 小时前
通俗易懂地讲解JAVA的BIO、NIO、AIO
java·nio
不要再敲了4 小时前
JDBC从入门到面试:全面掌握Java数据库连接技术
java·数据库·面试
潇I洒4 小时前
若依4.8.1打包war后在Tomcat无法运行,404报错的一个解决方法
java·tomcat·ruoyi·若依·404
Funcy5 小时前
XxlJob 源码分析05:执行器注册流程
java
Boop_wu5 小时前
[数据结构] 队列 (Queue)
java·jvm·算法