准备工作
- 使用spring boot搭建简单的项目
引入redis的包
compile('org.springframework.boot:spring-boot-starter-data-redis')
配置application.yml文件,添加如下内容(redis其他可以先使用默认配置)
spring: cache: type: redis redis: database: 0
源码分析
- 在需要缓存的方法上面加上@Cacheable
当请求进来的时候会触发CacheInterceptor拦截器,调用invoke方法
@Override public Object invoke(final MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); CacheOperationInvoker aopAllianceInvoker = new CacheOperationInvoker() { @Override public Object invoke() { try { return invocation.proceed(); } catch (Throwable ex) { throw new ThrowableWrapper(ex); } } }; try { return execute(aopAllianceInvoker, invocation.getThis(), method, invocation.getArguments()); } catch (CacheOperationInvoker.ThrowableWrapper th) { throw th.getOriginal(); } }
invoke方法会去调用CacheAspectSupport的execute方法