栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring系列之缓存Cache

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring系列之缓存Cache

Spring Cache 介绍

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 Cache介绍

定义了缓存操作的公共接口。

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。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/820517.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号