最近在工作过程中,使用到了注解 @Cacheable,因此记录一下,分享给朋友们。
@Cacheable
是 Spring 框架提供的注解,用于将方法的结果缓存起来,以提高方法的执行效率。
下面是使用 @Cacheable
注解的基本步骤:
1、在你的 Spring Boot 应用中引入相关依赖。在 pom.xml
文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2、在应用主类上添加 @EnableCaching
注解,以启用缓存功能。
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@EnableCaching
@SpringBootApplication
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
3、在需要被缓存的方法上添加 @Cacheable
注解,并指定缓存的名称和缓存的 key。
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class YourService {
@Cacheable(cacheNames = "yourCacheName", key = "#param")
public ResultType yourMethod(String param) {
// 方法的实现逻辑
}
}
代码解释:
cacheNames
属性指定了缓存的名称,可以是一个或多个名称的数组。缓存名称是用于区分不同缓存的标识。key
属性指定了缓存的键值,可以是 SpEL 表达式。方法的参数可以作为键值的一部分。ResultType
是方法返回的结果类型。
4、在需要使用缓存的地方调用被缓存的方法。当该方法第一次执行时,会将结果缓存起来。之后再次调用相同的方法时,会直接从缓存中获取结果,而不会再次执行方法体内的逻辑。