天津市免费建站,网站开发的工作制度,企业所得税优惠政策最新2023年,谷歌安装器注解Cacheable 是 Spring 框架中用于缓存数据的方法或类的注解。通过使用这个注解#xff0c;你可以避免重复计算和重复获取数据#xff0c;从而提高应用程序的性能。
基本用法
引入依赖
确保在你的项目中引入了 Spring Cache 相关的依赖。如果你使用的是 Spring Boot你可以避免重复计算和重复获取数据从而提高应用程序的性能。
基本用法
引入依赖
确保在你的项目中引入了 Spring Cache 相关的依赖。如果你使用的是 Spring Boot可以在 pom.xml 中添加以下依赖
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-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) {// ...
} 缓存失效CacheEvict
allEntriestrue清除所有缓存数据
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;
}