好得很程序员自学网

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

SpringBoot学习之基于注解的缓存

主要使用到的注解:

@Cacheable(放入缓存) 能够根据方法的请求参数对其结果进行缓存 @CachePut(修改缓存中的值) 能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用 @CachEvict(清除缓存) 能够根据一定的条件对缓存进行清空

使用步骤

1、@EnableCaching 这个注解,标注在 springboot 主启动类上,表示系统开启缓存。

?

1

2

3

4

5

6

7

@EnableCaching

@SpringBootApplication (scanBasePackages = CommonConstant.DEFAULT_PACKAGE_NAME)

public class PortalApp {

     public static void main(String[] args) {

         SpringApplication.run(PortalApp. class , args);

         }

     }

2、在对应需要进行缓存的方法上加入对应的注解即可;

注解属性介绍

@Cacheable() 的属性值及释义:

value/cacheNames = "demoCommon";//redis的第一层文件夹为demoCommon key="#id"; //系统自定义key值格式,相当于value下边一层 unless = "#result==null";//方法返回值结果为空时,不存入缓存;

代码示例如下:

?

1

2

3

4

5

//-- 根据id查询demo

@Cacheable (cacheNames = "demoCommon" , unless = "#result==null" , key= "#id" )

public Demo queryById(String id) {

     return demoMapper.queryById(id);

}

调用上述接口,会将接口返回的数据以下图格式存入redis,接口再使用此id作为参数查询时,会直接去缓存里拿:

@CachPut属性值及释义:

value/cacheNames = "demoCommon";//redis的第一层文件夹为demoCommon keyGenerator="myKeyGenerator"; //系统自定义key值格式,相当于value下边一层

调用示例如下:

?

1

2

3

4

5

@CachePut (value = "demoCommon" , key=# "#demo.id" )

public Demo updateById(Demo demo) {

     demoMapper.updateById(demo);

     return demo;

}

调用上图接口,会根据传入的id找到对应的key缓存的值,并修改缓存中的value;

@CachEvict属性值及释义:

value/cacheNames = "demoCommon";//redis的第一层文件夹为demoCommon key=#"#demo.id"; //系统自定义key值格式,相当于value下边一层 allEntries="true";// 是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空value/cachaeNames下边的所有缓存

?

1

2

3

4

5

@CacheEvict (value = "demoCommon" ,allEntries= "true" ,key = "#demo.id" )

public Demo deleteById(Demo demo) {

     demoMapper.deleteById(demo);

     return demo;

}

调用接口后,redis为:

@Caching

接口需要使用多个注解标签,则可使用此注解;示例如下:

?

1

2

3

4

5

6

7

8

9

@Caching (put = {

         @CachePut (value = "demoCommon1" , key = "#demo.id" )

         @CachePut (value = "demoCommon2" , key = "#demo.id" )

         @CachePut (value = "demoCommon3" , key = "#demo.id" )

})

public Demo updateByIdC(Demo demo) {

     demoMapper.updateById(demo);

     return demo;

}

总结

到此这篇关于SpringBoot基于注解的缓存的文章就介绍到这了,更多相关SpringBoot注解的缓存内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://juejin.cn/post/7078483379427442718

查看更多关于SpringBoot学习之基于注解的缓存的详细内容...

  阅读:17次