好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

深入理解Spring Cache框架

本文是缓存系列第三篇,前两篇分别介绍了 guava 和 jetcache。

前两篇我们讲了 guava 和 jetcache,它们都是缓存的具体实现,今天给大家分析一下 spring 框架 本身对这些缓存具体实现的支持和融合。使用 spring cache 将大大的减少我们的spring项目中缓存使用的复杂度,提高代码可读性。本文将从以下几个方面来认识spring cache框架。

背景

springcache 产生的背景其实与spring产生的背景有点类似。由于 java ee 系统框架臃肿、低效,代码可观性低,对象创建和依赖关系复杂, spring 框架出来了,目前基本上所有的java后台项目都离不开 spring 或 springboot (对 spring 的进一步简化)。现在项目面临高并发的问题越来越多,各类缓存的应用也增多,那么在通用的 spring 框架上,就需要有一种更加便捷简单的方式,来完成缓存的支持,就这样 springcache就出现了。

不过首先我们需要明白的一点是,springcache 并非某一种 cache 实现的技术,springcache 是一种缓存实现的通用技术,基于 spring 提供的 cache 框架,让开发者更容易将自己的缓存实现高效便捷的嵌入到自己的项目中。当然,springcache 也提供了本身的简单实现 noopcachemanager、concurrentmapcachemanager 等。通过 springcache,可以快速嵌入自己的cache实现。

用法

源码已分享至github: https://github测试数据/zhuzhenke/common-caches

注意点:

1、开启 enablecaching 注解,默认没有开启 cache。

2、配置 cachemanager。

?

1

2

3

4

5

6

@bean

@qualifier ( "concurrentmapcachemanager" )

@primary

concurrentmapcachemanager concurrentmapcachemanager() {

   return new concurrentmapcachemanager();

}

这里使用了 @primary 和 @qualifier 注解,@qualifier 注解是给这个 bean 加一个名字,用于同一个接口 bean 的多个实现时,指定当前 bean 的名字,也就意味着 cachemanager 可以配置多个,并且在不同的方法场景下使用。@primary 注解是当接口 bean 有多个时,优先注入当前 bean 。

现在拿 categoryservice 实现来分析。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

public class categoryservice {

 

   @caching (evict = { @cacheevict (value = categorycacheconstants.category_domain,

       key = "#category.getcategorycachekey()" ,

       beforeinvocation = true )})

   public int add(category category) {

     system.out.println( "模拟进行数据库交互操作......" );

     system.out.println( "cache became invalid,value:" + categorycacheconstants.category_domain

         + ",key:" + category.getcategorycachekey());

     return 1 ;

   }

 

   @caching (evict = { @cacheevict (value = categorycacheconstants.category_domain,

       key = "#category.getcategorycachekey()" ,

       beforeinvocation = true )})

   public int delete(category category) {

     system.out.println( "模拟进行数据库交互操作......" );

     system.out.println( "cache became invalid,value:" + categorycacheconstants.category_domain

         + ",key:" + category.getcategorycachekey());

     return 0 ;

   }

 

   @caching (evict = { @cacheevict (value = categorycacheconstants.category_domain,

       key = "#category.getcategorycachekey()" )})

   public int update(category category) {

     system.out.println( "模拟进行数据库交互操作......" );

     system.out.println( "cache updated,value:" + categorycacheconstants.category_domain

         + ",key:" + category.getcategorycachekey()

         + ",category:" + category);

     return 1 ;

   }

 

   @cacheable (value = categorycacheconstants.category_domain,

       key = "#category.getcategorycachekey()" )

   public category get(category category) {

     system.out.println( "模拟进行数据库交互操作......" );

     category result = new category();

     result.setcateid(category.getcateid());

     result.setcatename(category.getcateid() + "catename" );

     result.setparentid(category.getcateid() - 10 );

     return result;

   }

}

categoryservice 通过对 category 对象的数据库增删改查,模拟缓存失效和缓存增加的结果。使用非常简便,把注解加在方法上,则可以达到缓存的生效和失效方案。

深入源码

源码分析我们分为几个方面一步一步解释其中的实现原理和实现细节。源码基于 spring 4.3.7.release 分析。

发现

springcache 在方法上使用注解发挥缓存的作用,缓存的发现是基于 aop 的 pointcut 和 methodmatcher 通过在注入的 class 中找到每个方法上的注解,并解析出来。

首先看到 org.springframework.cache.annotation.springcacheannotationparser 类:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

protected collection<cacheoperation> parsecacheannotations(defaultcacheconfig cachingconfig, annotatedelement ae) {

  collection<cacheoperation> ops = null ;

 

  collection<cacheable> cacheables = annotatedelementutils.getallmergedannotations(ae, cacheable. class );

  if (!cacheables.isempty()) {

  ops = lazyinit(ops);

  for (cacheable cacheable : cacheables) {

   ops.add(parsecacheableannotation(ae, cachingconfig, cacheable));

  }

  }

  collection<cacheevict> evicts = annotatedelementutils.getallmergedannotations(ae, cacheevict. class );

  if (!evicts.isempty()) {

  ops = lazyinit(ops);

  for (cacheevict evict : evicts) {

   ops.add(parseevictannotation(ae, cachingconfig, evict));

  }

  }

  collection<cacheput> puts = annotatedelementutils.getallmergedannotations(ae, cacheput. class );

  if (!puts.isempty()) {

  ops = lazyinit(ops);

  for (cacheput put : puts) {

   ops.add(parseputannotation(ae, cachingconfig, put));

  }

  }

  collection<caching> cachings = annotatedelementutils.getallmergedannotations(ae, caching. class );

  if (!cachings.isempty()) {

  ops = lazyinit(ops);

  for (caching caching : cachings) {

   collection<cacheoperation> cachingops = parsecachingannotation(ae, cachingconfig, caching);

   if (cachingops != null ) {

   ops.addall(cachingops);

   }

  }

  }

 

  return ops;

}

这个方法会解析 cacheable、cacheevict、cacheput 和 caching 4个注解,找到方法上的这4个注解后,会将注解中的参数解析出来,作为后续注解生效的一个依据。这里举例说一下 cacheevict 注解。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

cacheevictoperation parseevictannotation(annotatedelement ae, defaultcacheconfig defaultconfig, cacheevict cacheevict) {

  cacheevictoperation.builder builder = new cacheevictoperation.builder();

 

  builder.setname(ae.tostring());

  builder.setcachenames(cacheevict.cachenames());

  builder.setcondition(cacheevict.condition());

  builder.setkey(cacheevict.key());

  builder.setkeygenerator(cacheevict.keygenerator());

  builder.setcachemanager(cacheevict.cachemanager());

  builder.setcacheresolver(cacheevict.cacheresolver());

  builder.setcachewide(cacheevict.allentries());

  builder.setbeforeinvocation(cacheevict.beforeinvocation());

 

  defaultconfig.applydefault(builder);

  cacheevictoperation op = builder.build();

  validatecacheoperation(ae, op);

 

  return op;

}

cacheevict 注解是用于缓存失效。这里代码会根据 cacheevict 的配置生产一个 cacheevictoperation 的类,注解上的 name、key、cachemanager 和 beforeinvocation 等都会传递进来。

另外需要将一下 caching 注解,这个注解通过 parsecachingannotation 方法解析参数,会拆分成 cacheable、cacheevict、cacheput 注解,也就对应我们缓存中的增加、失效和更新操作。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

collection<cacheoperation> parsecachingannotation(annotatedelement ae, defaultcacheconfig defaultconfig, caching caching) {

  collection<cacheoperation> ops = null ;

 

  cacheable[] cacheables = caching.cacheable();

  if (!objectutils.isempty(cacheables)) {

  ops = lazyinit(ops);

  for (cacheable cacheable : cacheables) {

   ops.add(parsecacheableannotation(ae, defaultconfig, cacheable));

  }

  }

  cacheevict[] cacheevicts = caching.evict();

  if (!objectutils.isempty(cacheevicts)) {

  ops = lazyinit(ops);

  for (cacheevict cacheevict : cacheevicts) {

   ops.add(parseevictannotation(ae, defaultconfig, cacheevict));

  }

  }

  cacheput[] cacheputs = caching.put();

  if (!objectutils.isempty(cacheputs)) {

  ops = lazyinit(ops);

  for (cacheput cacheput : cacheputs) {

   ops.add(parseputannotation(ae, defaultconfig, cacheput));

  }

  }

 

  return ops;

}

然后回到 abstractfallbackcacheoperationsource 类:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

public collection<cacheoperation> getcacheoperations(method method, class <?> targetclass) {

  if (method.getdeclaringclass() == object. class ) {

  return null ;

  }

 

  object cachekey = getcachekey(method, targetclass);

  collection<cacheoperation> cached = this .attributecache.get(cachekey);

 

  if (cached != null ) {

  return (cached != null_caching_attribute ? cached : null );

  }

  else {

  collection<cacheoperation> cacheops = computecacheoperations(method, targetclass);

  if (cacheops != null ) {

   if (logger.isdebugenabled()) {

   logger.debug( "adding cacheable method '" + method.getname() + "' with attribute: " + cacheops);

   }

   this .attributecache.put(cachekey, cacheops);

  }

  else {

   this .attributecache.put(cachekey, null_caching_attribute);

  }

  return cacheops;

  }

}

这里会将解析出来的 cacheoperation 放在当前 map<object, collection<cacheoperation>> attributecache = new concurrenthashmap<object, collection<cacheoperation>>(1024); 属性上,为后续拦截方法时处理缓存做好数据的准备。

注解产生作用

当访问 categoryservice.get(category) 方法时,会走到 cglibaopproxy.intercept() 方法,这也说明缓存注解是基于动态代理实现,通过方法的拦截来动态设置或失效缓存。方法中会通过 list<object> chain = this.advised.getinterceptorsanddynamicinterceptionadvice(method, targetclass); 来拿到当前调用方法的 interceptor 链。往下走会调用 cacheinterceptor 的 invoke 方法,最终调用 execute 方法,我们重点分析这个方法的实现。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

private object execute( final cacheoperationinvoker invoker, method method, cacheoperationcontexts contexts) {

  // special handling of synchronized invocation

  if (contexts.issynchronized()) {

  cacheoperationcontext context = contexts.get(cacheableoperation. class ).iterator().next();

  if (isconditionpassing(context, cacheoperationexpressionevaluator.no_result)) {

   object key = generatekey(context, cacheoperationexpressionevaluator.no_result);

   cache cache = context.getcaches().iterator().next();

   try {

   return wrapcachevalue(method, cache.get(key, new callable<object>() {

    @override

    public object call() throws exception {

    return unwrapreturnvalue(invokeoperation(invoker));

    }

   }));

   }

   catch (cache.valueretrievalexception ex) {

   // the invoker wraps any throwable in a throwablewrapper instance so we

   // can just make sure that one bubbles up the stack.

   throw (cacheoperationinvoker.throwablewrapper) ex.getcause();

   }

  }

  else {

   // no caching required, only call the underlying method

   return invokeoperation(invoker);

  }

  }

 

  // process any early evictions

  processcacheevicts(contexts.get(cacheevictoperation. class ), true ,

   cacheoperationexpressionevaluator.no_result);

 

  // check if we have a cached item matching the conditions

  cache.valuewrapper cachehit = findcacheditem(contexts.get(cacheableoperation. class ));

 

  // collect puts from any @cacheable miss, if no cached item is found

  list<cacheputrequest> cacheputrequests = new linkedlist<cacheputrequest>();

  if (cachehit == null ) {

  collectputrequests(contexts.get(cacheableoperation. class ),

   cacheoperationexpressionevaluator.no_result, cacheputrequests);

  }

 

  object cachevalue;

  object returnvalue;

 

  if (cachehit != null && cacheputrequests.isempty() && !hascacheput(contexts)) {

  // if there are no put requests, just use the cache hit

  cachevalue = cachehit.get();

  returnvalue = wrapcachevalue(method, cachevalue);

  }

  else {

  // invoke the method if we don't have a cache hit

  returnvalue = invokeoperation(invoker);

  cachevalue = unwrapreturnvalue(returnvalue);

  }

 

  // collect any explicit @cacheputs

  collectputrequests(contexts.get(cacheputoperation. class ), cachevalue, cacheputrequests);

 

  // process any collected put requests, either from @cacheput or a @cacheable miss

  for (cacheputrequest cacheputrequest : cacheputrequests) {

  cacheputrequest.apply(cachevalue);

  }

 

  // process any late evictions

  processcacheevicts(contexts.get(cacheevictoperation. class ), false , cachevalue);

 

  return returnvalue;

}

我们的方法没有使用同步,走到 processcacheevicts 方法。

?

1

2

3

4

5

6

7

8

private void processcacheevicts(collection<cacheoperationcontext> contexts, boolean beforeinvocation, object result) {

  for (cacheoperationcontext context : contexts) {

  cacheevictoperation operation = (cacheevictoperation) context.metadata.operation;

  if (beforeinvocation == operation.isbeforeinvocation() && isconditionpassing(context, result)) {

   performcacheevict(context, operation, result);

  }

  }

}

注意这个方法传入的 beforeinvocation 参数是 true,说明是方法执行前进行的操作,这里是取出 cacheevictoperation,operation.isbeforeinvocation(),调用下面方法:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

private void performcacheevict(cacheoperationcontext context, cacheevictoperation operation, object result) {

  object key = null ;

  for (cache cache : context.getcaches()) {

  if (operation.iscachewide()) {

   loginvalidating(context, operation, null );

   doclear(cache);

  }

  else {

   if (key == null ) {

   key = context.generatekey(result);

   }

   loginvalidating(context, operation, key);

   doevict(cache, key);

  }

  }

}

这里需要注意了,operation 中有个参数 cachewide,如果使用这个参数并设置为true,则在缓存失效时,会调用 clear 方法进行全部缓存的清理,否则只对当前 key 进行 evict 操作。本文中,doevict() 最终会调用到 concurrentmapcache的evict(object key) 方法,将 key 缓存失效。

回到 execute 方法,走到 cache.valuewrapper cachehit = findcacheditem(contexts.get(cacheableoperation.class)); 这一步,这里会根据当前方法是否有 cacheableoperation 注解,进行缓存的查询,如果没有命中缓存,则会调用方法拦截器 cacheinterceptor 的 proceed 方法,进行原方法的调用,得到缓存 key 对应的 value,然后通过 cacheputrequest.apply(cachevalue) 设置缓存。

?

1

2

3

4

5

6

7

public void apply(object result) {

  if ( this .context.canputtocache(result)) {

  for (cache cache : this .context.getcaches()) {

   doput(cache, this .key, result);

  }

  }

}

doput() 方法最终对调用到 concurrentmapcache 的 put 方法,完成缓存的设置工作。

最后 execute 方法还有最后一步 processcacheevicts(contexts.get(cacheevictoperation.class), false, cachevalue); 处理针对执行方法后缓存失效的注解策略。

优缺点

优点

方便快捷高效,可直接嵌入多个现有的 cache 实现,简写了很多代码,可观性非常强。

缺点

内部调用,非 public 方法上使用注解,会导致缓存无效。由于 springcache 是基于 spring aop 的动态代理实现,由于代理本身的问题,当同一个类中调用另一个方法,会导致另一个方法的缓存不能使用,这个在编码上需要注意,避免在同一个类中这样调用。如果非要这样做,可以通过再次代理调用,如 ((category)aopcontext.currentproxy()).get(category) 这样避免缓存无效。 不能支持多级缓存设置,如默认到本地缓存取数据,本地缓存没有则去远端缓存取数据,然后远程缓存取回来数据再存到本地缓存。

扩展知识点

动态代理:jdk、cglib代理。 springaop、方法拦截器。

demo

https://github测试数据/zhuzhenke/common-caches

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:http://HdhCmsTestimportnew测试数据/30640.html

查看更多关于深入理解Spring Cache框架的详细内容...

  阅读:17次