Spring Cache是spring3.1引入的基于注解的一个缓存技术,它是对缓存的一个抽象,有自己的缓存实现方案,在spring-context包下面org.springframework.cache包里面。
缓存实现体系-
spring-context
提供了对SpringCache的实现:ConcurrentMapCache。
-
spring-boot-starter-cache
实际上是引入了spring-context-support包,spring只是用这些缓存去实现了Cache接口,具体的实现还是要引入对应的缓存框架的jar包。
CaffeineCache:com.github.ben-manes.caffeine
EhCacheCache:net.sf.ehcache
JCacheCache:javax.cache.cache-api
定义了缓存操作的公共接口。
Cache源码
public interface Cache {
String getName();
Object getNativeCache();
@Nullable
ValueWrapper get(Object key);
@Nullable
T get(Object key, @Nullable Class type);
@Nullable
T get(Object key, Callable valueLoader);
void put(Object key, @Nullable Object value);
@Nullable
default ValueWrapper putIfAbsent(Object key, @Nullable Object value) {
ValueWrapper existingValue = get(key);
if (existingValue == null) {
put(key, value);
}
return existingValue;
}
void evict(Object key);
default boolean evictIfPresent(Object key) {
evict(key);
return false;
}
void clear();
default boolean invalidate() {
clear();
return false;
}
@FunctionalInterface
interface ValueWrapper {
@Nullable
Object get();
}
@SuppressWarnings("serial")
class ValueRetrievalException extends RuntimeException {
@Nullable
private final Object key;
public ValueRetrievalException(@Nullable Object key, Callable> loader, Throwable ex) {
super(String.format("Value for key '%s' could not be loaded using '%s'", key, loader), ex);
this.key = key;
}
@Nullable
public Object getKey() {
return this.key;
}
}
}
CacheManager
CacheManager介绍
Spring中央缓存管理器SPI
CacheManger源码
public interface CacheManager {
@Nullable
Cache getCache(String name);
Collection getCacheNames();
}
缓存框架
本地缓存
- Caffeine
Caffeine是使用Java8对Guava缓存的重写版本,在Spring Boot 2.0中将取代Guava,基于LRU算法实现,支持多种缓存过期策略。
- ehcache
是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的 CacheProvider。
- GuavaCache
Google Guava工具包中的一个非常方便易用的本地化缓存实现,基于LRU算法实现,支持多种缓存过期策略。
分布式缓存-
redis
-
memcached
-
Gemfire
- jetcache
使用本地和远程缓存:本地可以用caffeine和Linkedhashmap,远程可以使用redis。



