Spring 4.0.3是否支持Caffeine Cache集成及适配版本查询
Spring 4.0.3 与 Caffeine Cache 适配说明
- 首先明确:Spring 4.0.3 版本没有官方原生的Caffeine Cache集成支持,Spring官方对Caffeine的缓存抽象封装(对应
spring-context包下的org.springframework.cache.caffeine相关实现)是从Spring 4.3版本才正式加入的。 - 若需要在Spring 4.0.3中使用Caffeine Cache,可以通过自定义缓存管理器的方式手动集成,适配的Caffeine最高版本为2.x稳定分支,推荐使用
Caffeine 2.9.3,这是2.x分支的最终稳定版本,JDK依赖最低为6,和Spring 4.0.3的运行环境要求完全匹配。- 注意不要使用Caffeine 3.x及更高版本,该版本最低要求JDK 8,且依赖的Spring基础API版本更高,会直接出现类不兼容、方法缺失等报错。
手动集成示例代码
Maven依赖配置
<dependency> <groupId>com.github.benmanes.caffeine</groupId> <artifactId>caffeine</artifactId> <version>2.9.3</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.0.3.RELEASE</version> </dependency>
自定义缓存配置类
import com.github.benmanes.caffeine.cache.Caffeine; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.support.SimpleCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.cache.concurrent.ConcurrentMapCache; import java.util.Arrays; import java.util.concurrent.TimeUnit; @Configuration @EnableCaching public class CaffeineCacheConfig { @Bean public CacheManager cacheManager() { SimpleCacheManager cacheManager = new SimpleCacheManager(); // 自定义名称为userCache的缓存实例,底层使用Caffeine实现 Cache userCache = new ConcurrentMapCache("userCache", Caffeine.newBuilder() .expireAfterWrite(30, TimeUnit.MINUTES) .maximumSize(1000) .build() .asMap(), false); cacheManager.setCaches(Arrays.asList(userCache)); return cacheManager; } }
注意事项
- 手动集成方式无法使用Spring 4.3+提供的
CaffeineCacheManager等原生封装类,所有缓存规则、多缓存实例管理都需要自行实现 - 缓存注解
@Cacheable、@CachePut、@CacheEvict的使用逻辑和原生Spring缓存一致,不需要额外调整
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

