spring cache基本使用
时间: 2023-10-21 09:53:12 浏览: 58
Spring Cache是Spring框架提供的一个缓存抽象层,可以方便地在应用中添加缓存功能。下面是Spring Cache的基本使用方法:
1. 添加依赖:在项目的pom.xml文件中添加Spring Cache的依赖项。
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
```
2. 配置缓存管理器:在配置类中添加@EnableCaching注解,并配置缓存管理器。
```java
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("cacheName")));
return cacheManager;
}
}
```
3. 在需要缓存的方法上添加缓存注解:使用@Cacheable注解来标记需要进行缓存的方法。
```java
@Service
public class MyService {
@Cacheable("cacheName")
public String getData(String key) {
// 这里是从数据库或其他外部资源获取数据的逻辑
return data;
}
}
```
4. 测试缓存功能:在测试类中调用被缓存的方法,多次调用可以看到第一次调用时会执行方法体,后续调用则从缓存中获取结果。
```java
@SpringBootTest
class CacheTest {
@Autowired
private MyService myService;
@Test
public void testCache() {
String result1 = myService.getData("key");
String result2 = myService.getData("key");
// result1和result2的值应该相同,第二次调用从缓存中获取结果
}
}
```
以上是Spring Cache的基本使用方法,通过配置缓存管理器和使用@Cacheable注解,可以轻松地在Spring应用中添加缓存功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)