注解Cacheable
是 Spring 框架中用于緩存數據的方法或類的注解。通過使用這個注解,你可以避免重復計算和重復獲取數據,從而提高應用程序的性能。
基本用法
- 引入依賴
確保在你的項目中引入了 Spring Cache 相關的依賴。如果你使用的是 Spring Boot,可以在 pom.xml
中添加以下依賴:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId>
</dependency>
- 啟用緩存
在主類或配置類上使用 @EnableCaching
注解來啟用緩存功能。
@SpringBootApplication
@EnableCaching
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
- 使用
@Cacheable
注解
在需要緩存的方法上使用 @Cacheable
注解。
@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.properties
或 application.yml
)中進行配置。
- 使用 ConcurrentMapCache本地緩存
spring:cache:type: simple
- 使用 Redis 作為緩存
spring:cache:type: redisredis:host: 172.1.1.11port: 6379
高級用法
- 緩存條件:
condition
使用 condition
屬性指定緩存條件,只換成id大于10的數據緩存
@Cacheable(value = "lizz:users", condition = "#id > 10")
public User getUserById(Long id) {// ...
}
- ?自定義緩存鍵
?使用 key
屬性自定義緩存鍵。
@Cacheable(value = "users", key = "#root.methodName + #id")
public User getUserById(Long id) {// ...
}
- ?同步更新:sync
sync=true時,如果多個線程同時訪問緩存中沒有的數據,只有一個線程會執行方法以加載數據,其他線程會等待加載完成并獲取相同的結果。這可以防止緩存穿透(即多個線程同時訪問緩存時都繞過緩存直接訪問底層存儲)。
@Cacheable(value = "users", sync = true)
public User getUserById(Long id) {// ...
}
緩存失效:@CacheEvict
- allEntries=true:清除所有緩存數據
@CacheEvict(value = "lizz:users", allEntries = true)
public void clearCache() {// //清除全部緩存相關的其他業務操作
}
- key = "#id" :清除緩存集合中指定key的數據
@CacheEvict(value = "lizz:users", key = "#id")
public void delUser(Long id) {//清除id緩存相關的其他業務操作
}
- 緩存同步:
@CachePut
?使用 @CachePut
注解更新緩存。
@CachePut(value = "lizz:users", key = "#user.id")
public User updateUser(User user) {// 更新用戶的邏輯return user;
}
結合緩存組件
-
引入caffeine
<!--快速本地緩存--><dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId></dependency>
- 使用caffeine作為springcache管理
@EnableCaching
@Configuration
public class CaffeineCacheConfig {@Beanpublic 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);}
}
?