Spring Cache 概述
Spring Cache 是 Spring 框架提供的一个缓存抽象,用于简化缓存的管理。它允许开发者在不依赖特定缓存实现的情况下,通过注解或编程方式实现方法级别的缓存。Spring Cache 支持多种缓存提供者,如 EHCache、Caffeine、Redis、Guava 等。
Spring Cache 的核心概念包括:
-
缓存接口(Cache):定义了基本的缓存操作,如
get、put、evict等。 -
缓存管理器(CacheManager):用于管理多个缓存实例。
-
缓存注解:
@Cacheable:用于标记方法的返回值会被缓存。@CacheEvict:用于清除缓存。@CachePut:更新缓存而不影响方法的实际调用。@Caching:组合多个缓存操作。
应用场景
-
数据库查询缓存:在高并发的应用中,频繁的数据库查询可能会影响性能。通过 Spring Cache,可以缓存查询结果,减少数据库访问次数。
-
计算密集型任务缓存:对于一些耗时的计算操作,将结果缓存起来,可以避免重复计算,提高性能。
-
Web应用数据缓存:在 Web 应用中,某些不经常变化的数据可以缓存,减少对外部服务或数据库的请求,降低延迟。
-
配置数据缓存:将一些配置信息缓存起来,避免频繁读取配置文件或远程配置服务。
示例代码
以下是一个使用 Spring Cache 的简单示例:
1. 引入依赖
在 pom.xml 中添加 Spring Cache 和缓存提供者的依赖(例如使用 Caffeine 缓存):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
2. 配置缓存
在 Spring Boot 应用中配置缓存:
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("books");
}
@Bean
public Caffeine<Object, Object> caffeineConfig() {
return Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(100);
}
@Bean
public CacheManager caffeineCacheManager(Caffeine<Object, Object> caffeine) {
return new CaffeineCacheManager("books", caffeine);
}
}
3. 使用缓存注解
在服务层使用 @Cacheable 注解来缓存方法的返回值:
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class BookService {
@Cacheable("books")
public Book findBookByIsbn(String isbn) {
// 模拟耗时操作,如数据库查询
simulateSlowService();
return new Book(isbn, "Some Book Title");
}
private void simulateSlowService() {
try {
Thread.sleep(3000L); // 模拟慢速服务
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
4. 测试缓存
通过调用服务层方法来测试缓存功能:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class AppRunner implements CommandLineRunner {
@Autowired
private BookService bookService;
@Override
public void run(String... args) throws Exception {
System.out.println("Fetching book...");
System.out.println(bookService.findBookByIsbn("isbn-1234"));
System.out.println("Fetching book again...");
System.out.println(bookService.findBookByIsbn("isbn-1234"));
}
}
第一次调用 findBookByIsbn("isbn-1234") 时,方法会执行并返回结果,同时结果会被缓存。第二次调用时,将直接从缓存中获取数据,不再执行耗时操作。
代码解释
-
@EnableCaching:开启 Spring 的缓存支持。 -
缓存管理器:
- 使用
ConcurrentMapCacheManager作为简单的缓存管理器。 - 或者使用
CaffeineCacheManager来使用 Caffeine 作为缓存实现。
- 使用
-
@Cacheable注解:标记的方法会将返回值缓存,缓存的 key 是方法参数(如isbn)。 -
缓存生效:第二次调用同样的方法时,结果会从缓存中获取,避免重复执行耗时操作。
总结
Spring Cache 提供了一种简单而强大的缓存机制,适用于各种场景,如数据库查询缓存、计算结果缓存等。通过合理配置和使用缓存,能够显著提高应用程序的性能和响应速度。

2494






