好得很程序员自学网

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

浅谈Spring boot cache使用和原理

缓存要解决的问题:一个程序的瓶颈在于数据库,我们也知道内存的速度是大大快于硬盘的速度的。当我们需要重复地获取相同的数据的时候,我们一次又一次的请求数据库或者远程服务,导致大量的时间耗费在数据库查询或者远程方法调用上,导致程序性能的恶化,这便是数据缓存要解决的问题。

类似的缓存技术有:redis、eh cache 、guava等,现在一般常用的为redis。

spring 3.1 引入了激动人心的基于注释(annotation)的缓存(cache)技术,它本质上不是一个具体的缓存实现方案(例如ehcache 或者 oscache),而是一个对缓存使用的抽象,通过在既有代码中添加少量它定义的各种 annotation,即能够达到缓存方法的返回对象的效果。

spring 的缓存技术还具备相当的灵活性,不仅能够使用 spel(spring expression language)来定义缓存的 key 和各种 condition,还提供开箱即用的缓存临时存储方案,也支持和主流的专业缓存例如 ehcache 集成。

其特点总结如下:

1. 通过少量的配置 annotation 注释即可使得既有代码支持缓存
2. 支持开箱即用 out-of-the-box,即不用安装和部署额外第三方组件即可使用缓存
3. 支持 spring express language,能使用对象的任何属性或者方法来定义缓存的 key 和 condition
4. 支持 aspectj,并通过其实现任何方法的缓存支持
5. 支持自定义 key 和自定义缓存管理者,具有相当的灵活性和扩展性

一、spring boot cache原理

第一步、自动配置类;

自动启动类:cacheautoconfiguration

属性配置:cacheproperties

主启动类添加:@enablecaching注解

cache pom添加:

?

1

2

3

4

<dependency>

   <groupid>org.springframework.boot</groupid>

   <artifactid>spring-boot-starter-cache</artifactid>

</dependency>

第二步、从缓存的配置类 中获取 多个cache

cacheconfigurationimportselector.selectimports()方法获取

?

1

2

3

4

5

6

7

8

9

10

11

12

13

static class cacheconfigurationimportselector implements importselector {

     @override

     public string[] selectimports(annotationmetadata importingclassmetadata) {

       cachetype[] types = cachetype.values();

       string[] imports = new string[types.length];

       for ( int i = 0 ; i < types.length; i++) {

         imports[i] = cacheconfigurations.getconfigurationclass(types[i]);

       }

       return imports;

     }

}

获取结果:simplecacheconfiguration 默认cache

?

1

2

3

4

5

6

7

8

9

10

11

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

第三步:simplecacheconfiguration.cachemanager()

此方法中给容器中注册了一个cachemanager组件:类型为concurrentmapcachemanager

?

1

2

3

4

5

6

7

8

9

@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);

}

第四步:查看获取缓存方法getcache()

concurrentmapcachemanager 类里,数据都存储到为concurrentmap 中

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

public cache getcache(string name) {

   cache cache = this .cachemap.get(name); //cachemap 为concurrentmap 类型,获取一个cache组件

   if (cache == null && this .dynamic) {

    synchronized ( this .cachemap) {

      cache = this .cachemap.get(name); //cahcemap不为空获取

      if (cache == null ) {

       //可以获取或者创建concurrentmapcache类型的缓存组件;他的作用将数据保存在concurrentmap中;

       cache = createconcurrentmapcache(name); 

       this .cachemap.put(name, cache); //concurrentmapcache.lookup();

      }

    }

   }

   return cache;

}

二、cacheable运行流程:

​ @cacheable: 1、方法运行之前,先去查询cache(缓存组件),按照cachenames指定的名字获取; (cachemanager先获取相应的缓存),第一次获取缓存如果没有cache组件会自动创建。 2、去cache中查找缓存的内容(concurrentmapcache.lookup()方法中去查找),使用一个key,默认就是方法的参数; key是按照某种策略生成的;默认是使用keygenerator生成的,默认使用simplekeygenerator生成key; simplekeygenerator生成key的默认策略; 如果没有参数;key=new simplekey(); 如果有一个参数:key=参数的值 如果有多个参数:key=new simplekey(params);

?

1

2

3

4

5

6

7

8

9

10

11

12

13

//这个方法 simplekeygenerator.generatekey()  方法生成key

public static object generatekey(object... params) {

   if (params.length == 0 ) {

    return simplekey.empty;

   }

   if (params.length == 1 ) { //如果只有一个参数,直接返回这个参数为key

    object param = params[ 0 ];

    if (param != null && !param.getclass().isarray()) {

      return param;

    }

   }

   return new simplekey(params);

}

3、没有查到缓存就调用目标方法; 4、将目标方法返回的结果,放进缓存中concurrentmapcache.put();

@cacheable标注的方法执行之前先来检查缓存中有没有这个数据,默认按照参数的值作为key去查询缓存, 如果没有就运行方法并将结果放入缓存;以后再来调用就可以直接使用缓存中的数据;

​ 核心: 1)、使用cachemanager【concurrentmapcachemanager】按照名字得到cache【concurrentmapcache】组件 2)、key使用keygenerator生成的,默认是simplekeygenerator

详细执行流程:concurrentmapcache.lookup()上断点查看,执行过程

?

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

//第一步cacheaspectsupport 中execute()

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

//第二步 cacheaspectsupport

private cache.valuewrapper findcacheditem(collection<cacheoperationcontext> contexts) {

   object result = cacheoperationexpressionevaluator.no_result;

   for (cacheoperationcontext context : contexts) {

     if (isconditionpassing(context, result)) {

       object key = generatekey(context, result); //获取key

       cache.valuewrapper cached = findincaches(context, key);

       if (cached != null ) {

         return cached;

       }

       else {

         if (logger.istraceenabled()) {

           logger.trace( "no cache entry for key '" + key + "' in cache(s) " + context.getcachenames());

         }

       }

     }

   }

   return null ;

}

//第三步:cacheaspectsupport.findincaches()

//第四步:abstractcacheinvoker.doget()

//第五步:abstractvalueadaptingcache.get();

@override

public valuewrapper get(object key) {

     object value = lookup(key);

     return tovaluewrapper(value);

}

// 第六步:concurrentmapcache.lookup(); 从concurrentmap 中根据key获取值

@override

protected object lookup(object key) {

     return this .store.get(key);

}

三、cacheable 注解的几个属性:

1、cachenames/value:指定缓存组件的名字;将方法的返回结果放在哪个缓存中,是数组的方式,可以指定 多个缓存;

2、key:缓存数据使用的key;可以用它来指定。默认是使用方法参数的值 1-方法的返回值

​ 编写spel; #i d;参数id的值 #a0 #p0 #root.args[0]

​ getemp[2]

3、keygenerator:key的生成器;可以自己指定key的生成器的组件id

​ key/keygenerator:二选一使用;

4、cachemanager:指定缓存管理器;或者cacheresolver指定获取解析器

5、condition:指定符合条件的情况下才缓存;

​ ,condition = "#id>0"

​ condition = "#a0>1":第一个参数的值》1的时候才进行缓存

6、unless:否定缓存;当unless指定的条件为true,方法的返回值就不会被缓存;可以获取到结果进行判断

​ unless = "#result == null"

​ unless = "#a0==2":如果第一个参数的值是2,结果不缓存;

7、sync:是否使用异步模式;异步模式的情况下unless不支持

四、cache使用:

1.cacheable的使用

?

1

2

3

4

5

6

@cacheable (value = { "emp" } /*,keygenerator = "mykeygenerator",condition = "#a0>1",unless = "#a0==2"*/ )

public employee getemp(integer id){

   system.out.println( "查询" +id+ "号员工" );

   employee emp = employeemapper.getempbyid(id);

   return emp;

}

2.自定义keygenerator:

?

1

2

3

4

5

6

7

8

9

10

@bean ( "mykeygenerator" )

public keygenerator keygenerator(){

   return new keygenerator(){

     @override

     public object generate(object target, method method, object... params) {

       return method.getname()+ "[" + arrays.aslist(params).tostring()+ "]" ;

     }

   };

}

3.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

28

/**

    * @cacheput:既调用方法,又更新缓存数据;同步更新缓存

    * 修改了数据库的某个数据,同时更新缓存;

    * 运行时机:

    * 1、先调用目标方法

    * 2、将目标方法的结果缓存起来

    *

    * 测试步骤:

    * 1、查询1号员工;查到的结果会放在缓存中;

    *     key:1 value:lastname:张三

    * 2、以后查询还是之前的结果

    * 3、更新1号员工;【lastname:zhangsan;gender:0】

    *     将方法的返回值也放进缓存了;

    *     key:传入的employee对象 值:返回的employee对象;

    * 4、查询1号员工?

    *   应该是更新后的员工;

    *     key = "#employee.id":使用传入的参数的员工id;

    *     key = "#result.id":使用返回后的id

    *       @cacheable的key是不能用#result

    *   为什么是没更新前的?【1号员工没有在缓存中更新】

    *

    */

   @cacheput (value = "emp" ,key = "#result.id" )

   public employee updateemp(employee employee){

     system.out.println( "updateemp:" +employee);

     employeemapper.updateemp(employee);

     return employee;

   }

4.cacheevict 缓存清除

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

/**

  * @cacheevict:缓存清除

  * key:指定要清除的数据

  * allentries = true:指定清除这个缓存中所有的数据

  * beforeinvocation = false:缓存的清除是否在方法之前执行

  *   默认代表缓存清除操作是在方法执行之后执行;如果出现异常缓存就不会清除

  *

  * beforeinvocation = true:

  *   代表清除缓存操作是在方法运行之前执行,无论方法是否出现异常,缓存都清除

  *

  *

  */

@cacheevict (value= "emp" ,beforeinvocation = true ,key = "#id" )

public void deleteemp(integer id){

   system.out.println( "deleteemp:" +id);

   //employeemapper.deleteempbyid(id);

   int i = 10 / 0 ;

}

5.caching 复杂配置

?

1

2

3

4

5

6

7

8

9

10

11

12

13

// @caching 定义复杂的缓存规则

@caching (

    cacheable = {

      @cacheable ( /*value="emp",*/key = "#lastname")

    },

    put = {

      @cacheput(/*value="emp",*/key = "#result.id"),

      @cacheput(/*value="emp",*/ key = "#result.email" )

    }

)

public employee getempbylastname(string lastname){

   return employeemapper.getempbylastname(lastname);

}

6.cacheconfig缓存清除

?

1

2

3

@cacheconfig (cachenames= "emp" ,cachemanager = "employeecachemanager" ) //抽取缓存的公共配置

@service

public class employeeservice {

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

原文链接:https://blog.csdn.net/yangliuhbhd/article/details/80626468

查看更多关于浅谈Spring boot cache使用和原理的详细内容...

  阅读:39次