springboot缓存-@Cacheable

关键字:

CacheManage:缓存接口,定义缓存操作。实现有:RedisCache、EhCacheCache、ConcurrentMapCache等

@Cacheable :缓存管理器,管理各种缓存(Cache)组件

keyGenerator:缓存数据时key生成策略

使用方式:

在查询方法上使用@Cacheable注解,①当此方法第一次被调用的时候将会先查询缓存里是否有结果,如果在缓存内没有查询到,②将会使用此方法到数据库内查询数据查询到的数据将会被存入缓存中。

@Cacheable(cacheNames = {"emp"})
public Employee getEmp(Integer id){
     System.out.println("查询"+id+"员工");
     Employee emp = employeeMapper.getEmpById(id);
     return emp;
 }

原理:

1、自动配置类:CacheAutoConfiguration ,用来选择哪一种缓存技术
*  org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration
*  org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration
*  org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
* org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration
* org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
* org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
* org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
* org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
* org.springframework.boot.autoconfigure.cache.GuavaCacheConfiguration
* org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration
* org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration

一共有以上这些缓存技术,如果使用redis,就应该配置RedisCacheConfiguration。

2.在没有任何配置的情况下,默认使用SimpleCacheConfiguration

3.SimpleCacheConfiguration配置类默认生效。这个配置类给容器中注册了一个CacheManager

    @Bean
	public ConcurrentMapCacheManager cacheManager() {
		ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager();
		List<String> cacheNames = this.cacheProperties.getCacheNames();
		if (!cacheNames.isEmpty()) {
			cacheManager.setCacheNames(cacheNames);
		}
		return this.customizerInvoker.customize(cacheManager);
	}

4.生成一个CacheManager会返回一个ConcurrentMapCacheManager,该类会先通过Name查找缓存Cache,如果没有找到,就会生成一个Cache

@Override
	public Cache getCache(String name) {
		Cache cache = this.cacheMap.get(name);
		if (cache == null && this.dynamic) {
			synchronized (this.cacheMap) {
				cache = this.cacheMap.get(name);
				if (cache == null) {
					cache = createConcurrentMapCache(name);
					this.cacheMap.put(name, cache);
				}
			}
		}
		return cache;
	}

5.通过key,key默认是通过SimpleKeyGenerator类生成的,生成后的key(可以是传进去的参数值)会在cache中查询。

public static Object generateKey(Object... params) {
		if (params.length == 0) {
			return SimpleKey.EMPTY;
		}
		if (params.length == 1) {
			Object param = params[0];
			if (param != null && !param.getClass().isArray()) {
				return param;
			}
		}
		return new SimpleKey(params);
	}

6.如果没有在Cache中查询到,将会查询数据库,查询后的结果将会存到Cache,第二次查找该key的值就可以在Cache中查询到了。


版权声明:本文为IhavePenapple原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。