springboot集成jetcache及应用

来源:互联网 发布:javascript隐藏div 编辑:程序博客网 时间:2024/06/09 13:24

  JetCache源码在github上的地址    https://github.com/alibaba/jetcache

   JetCache需要JDK1.8、Spring Framework4.0.8以上版本。

   jetCache是对springCache的一次封装,强大了其功能;那么JetCache可以做什么?  (官方解释)

  • 通过更简单易用的统一API对缓存进行操作,屏蔽缓存实现的底层差异。当前有四个实现,Redis、Tair(此部分未在github开源)、CaffeineCache和一个简易的LinkedHashMapCache。

  • 通过注解方式创建并配置缓存实例

  • 通过注解方式为方法增加并配置缓存

  • 支持两级甚至多级缓存

  • 缓存各个区域的统计

  • 自动刷新(2.2)

  • 异步接口(2.2,使用redis的luttece客户端)

      在本例中之讲解CaffeineCache和Redis的用法,环境是SpringBoot

      maven中加入对jar的支持,如下,目前作者一直在更新

  1.   <dependency>
  2.     <groupId>com.alicp.jetcache</groupId>
  3.     <artifactId>jetcache-starter-redis</artifactId>
  4.     <version>2.2.0.Beta1</version>
  5. </dependency>
  6. <dependency>
  7.     <groupId>redis.clients</groupId>
  8.     <artifactId>jedis</artifactId>
  9.     <version>2.9.0</version>
  10. </dependency>

注意jedis的版本,低版本的可能会报异常;

其次在配置文件中加入对两种类型缓存的配置,大致如下:

  1. jetcache.statIntervalMinutes=10
  2. jetcache.hiddenPackages=com.zte
  3. jetcache.local.default.type=caffeine
  4. jetcache.local.default.limit=50
  5. jetcache.local.default.defaultExpireInMillis=300000
  6.  
  7. jetcache.remote.default.type=redis
  8. jetcache.remote.default.poolConfig.minIdle=5
  9. jetcache.remote.default.poolConfig.maxIdle=50
  10. jetcache.remote.default.poolConfig.maxTotal=100
  11. jetcache.remote.default.host=127.0.0.1
  12. jetcache.remote.default.password=zte@123
  13. jetcache.remote.default.port=6379
  14. jetcache.remote.default.defaultExpireInMillis=300000
  15. jetcache.remote.default.keyPrefix=xxPro
  16. jetcache.remote.default.keyConvertor: fastjson

配置参数的大致解释如下:

属性默认值说明jetcache.statIntervalMinutes0统计间隔,0表示不统计jetcache.hiddenPackages@Cached和@CreateCache自动生成name的时候,为了不让name太长,hiddenPackages指定的包名前缀被截掉jetcache.[local|remote].${area}.type缓存类型。tair、redis为当前支持的远程缓存;linkedhashmap、caffeine为当前支持的本地缓存类型jetcache.[local|remote].${area}.keyConvertorkey转换器,使用方法缓存必须指定keyConvertor,当前只有一个已经实现的keyConvertor:fastjsonjetcache.[local|remote].${area}.valueEncoderjava仅remote类型的缓存需要指定,可选java和kryojetcache.[local|remote].${area}.valueDecoderjava仅remote类型的缓存需要指定,可选java和kryojetcache.[local|remote].${area}.limit100仅local类型的缓存需要指定,限定每个缓存实例的最大元素。注意是每个缓存实例的限制,而不是全部,比如这里指定100,然后用@CreateCache创建了两个缓存实例(并且注解上没有设置localLimit属性),那么每个缓存实例的限制都是100jetcache.[local|remote].${area}.defaultExpireInMillis无穷大以毫秒为单位指定超时时间,在2.2版本以后,更名为expireAfterWriteInMillis,原先的defaultExpireInMillis仍然可以使用jetcache.local.${area}.expireAfterAccessInMillis0需要jetcache2.2以上,以毫秒为单位,指定多长时间没有访问,就让缓存失效,当前只有本地缓存支持

一切就绪,开始使用

JetCache有两种支持缓存的方式,一种是基于方法的,一种是可以自己定义创建的;

1.基于方法的缓存方式

实现方式是spring aop,采用注解的方式@cache

我们看下这个注解的源码,可以大致了解上面的默认配置文件的含义以及该注解的用法;源码如下

  1. @Documented
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Target(ElementType.METHOD)
  4. public @interface Cached {
  5.     String area() default CacheConsts.DEFAULT_AREA;
  6.     String name() default CacheConsts.UNDEFINED_STRING;
  7.     boolean enabled() default CacheConsts.DEFAULT_ENABLED;
  8.     TimeUnit timeUnit() default TimeUnit.SECONDS;
  9.     int expire() default CacheConsts.UNDEFINED_INT;
  10.     CacheType cacheType() default CacheType.REMOTE;
  11.     int localLimit() default CacheConsts.UNDEFINED_INT;
  12.     String serialPolicy() default CacheConsts.UNDEFINED_STRING;
  13.     String keyConvertor() default CacheConsts.UNDEFINED_STRING;
  14.     boolean cacheNullValue() default CacheConsts.DEFAULT_CACHE_NULL_VALUE;
  15.     /**
  16.      * Expression attribute used for conditioning the method caching.
  17.      * <p>Default is "", meaning the method is always cached.
  18.      */
  19.     String condition() default CacheConsts.UNDEFINED_STRING;
  20.     /**
  21.      * Expression attribute used to veto method caching.
  22.      * <p>Unlike {@link #condition()}, this expression is evaluated after the method
  23.      * has been called and can therefore refer to the {@code result}. Default is "",
  24.      * meaning that caching is never vetoed.
  25.      */
  26.     String unless() default CacheConsts.UNDEFINED_STRING;
  27. }

首先是作用在方法之上,运行期起作用,而该注解下面的参数,全部存在默认的配置,也就是说我们若是不指定的情况下,就会加载默认的配置。在业务中针对不同的方法可能需要的expire的时间不一样,这里可以指定。

基于方法注解的用法如下:

首先加入对cache的注解支持---@EnableMethodCache(basePackages="com.xx")

后面的包名是使用该注解的方法所在的包的全路径

然后在方法上采用该注解即可,示例如下:


  1. @Cached(name="xxx.xxx.xx",expire=30,timeUnit=TimeUnit.MINUTES)
  2. public Page<Project> xxxxxxxx(String type,Pageable pageable){
  3. return repository.xxxxxx(type,pageable);
  4. }

2.自定义缓存的方式

JetCache中提供了@createCache的注解的支持,可以自己定义的cache,灵活性比较高,下面讲一下具体的用法

加入createCache的支持----@EnableCreateCacheAnnotation

根据需要自己定义一个cache,示例代码如下:


  1. @CreateCache
  2. Cache<String, Object> jetcache;

具体使用:

  1. if (jetcache.get("project_"+project.getId())==null) {
  2. parent=xxxxService.find((long)xxxxxx.getParentId());
  3. jetcache.put("project_"+project.getId(), parent);
  4. }else{
  5. parent=(Project) jetcache.get("project_"+project.getId());
  6. }

用法跟Map类似;

需要讲解的一点就是JetCache支持二级缓存,可以直接通过cacheType来设置,灵活性很高。

按照项目中来举个例子

在配置文件中为配置了redis和caffeine两种,可以通过代码的cacheType来设置具体将缓存放到哪里。

JetCache还有一个优点不得不提,这也是在应用之后不经意之间发现的,那就是JetCache的统计报表功能,不多讲,看下面代码就可明白

  1. cache                                                            |       qps|   rate|           get|           hit|          fail|        expire|avgLoadTime|maxLoadTime
  2. -----------------------------------------------------------------+----------+-------+--------------+--------------+--------------+--------------+-----------+-----------
  3. default_c.z.d.p.c.ProjectController.jetcache                     |      1.25|100.00%|           108|           108|             0|             0|        0.0|          0
  4. ..._c.z.d.p.s.p.i.ProjectServiceImpl.findByDevopsId(Lj.l.String;)|      0.17|100.00%|            14|            14|             0|             0|        0.0|          0
  5. default_c.z.d.p.s.p.i.ProjectServiceImpl.getNewProjects()        |      0.02|100.00%|             2|             2|             0|             0|        0.0|          0
  6. ...ctServiceImpl.getProjectByType(Lj.l.String;Lo.s.d.d.Pageable;)|      0.02|100.00%|             2|             2|             0|             0|        0.0|          0
  7. -----------------------------------------------------------------+----------+-------+--------------+--------------+--------------+--------------+-----------+-----------
原创粉丝点击