当前位置: 移动技术网 > IT编程>开发语言>Java > spring boot+spring cache实现两级缓存(redis+caffeine)

spring boot+spring cache实现两级缓存(redis+caffeine)

2019年07月19日  | 移动技术网IT编程  | 我要评论

spring boot中集成了spring cache,并有多种缓存方式的实现,如:redis、caffeine、jcache、ehcache等等。但如果只用一种缓存,要么会有较大的网络消耗(如redis),要么就是内存占用太大(如caffeine这种应用内存缓存)。在很多场景下,可以结合起来实现一、二级缓存的方式,能够很大程度提高应用的处理效率。

内容说明:

  1. 缓存、两级缓存
  2. spring cache:主要包含spring cache定义的接口方法说明和注解中的属性说明
  3. spring boot + spring cache:rediscache实现中的缺陷
  4. caffeine简介
  5. spring boot + spring cache 实现两级缓存(redis + caffeine)

缓存、两级缓存

简单的理解,缓存就是将数据从读取较慢的介质上读取出来放到读取较快的介质上,如磁盘-->内存。平时我们会将数据存储到磁盘上,如:数据库。如果每次都从数据库里去读取,会因为磁盘本身的io影响读取速度,所以就有了像redis这种的内存缓存。可以将数据读取出来放到内存里,这样当需要获取数据时,就能够直接从内存中拿到数据返回,能够很大程度的提高速度。但是一般redis是单独部署成集群,所以会有网络io上的消耗,虽然与redis集群的链接已经有连接池这种工具,但是数据传输上也还是会有一定消耗。所以就有了应用内缓存,如:caffeine。当应用内缓存有符合条件的数据时,就可以直接使用,而不用通过网络到redis中去获取,这样就形成了两级缓存。应用内缓存叫做一级缓存,远程缓存(如redis)叫做二级缓存

spring cache

当使用缓存的时候,一般是如下的流程:

从流程图中可以看出,为了使用缓存,在原有业务处理的基础上,增加了很多对于缓存的操作,如果将这些耦合到业务代码当中,开发起来就有很多重复性的工作,并且不太利于根据代码去理解业务。

spring cache是spring-context包中提供的基于注解方式使用的缓存组件,定义了一些标准接口,通过实现这些接口,就可以通过在方法上增加注解来实现缓存。这样就能够避免缓存代码与业务处理耦合在一起的问题。spring cache的实现是使用spring aop中对方法切面(methodinterceptor)封装的扩展,当然spring aop也是基于aspect来实现的。

spring cache核心的接口就两个:cache和cachemanager

cache接口

提供缓存的具体操作,比如缓存的放入、读取、清理,spring框架中默认提供的实现有:

除了rediscache是在spring-data-redis包中,其他的基本都是在spring-context-support包中

#cache.java

package org.springframework.cache;

import java.util.concurrent.callable;

public interface cache {

 // cachename,缓存的名字,默认实现中一般是cachemanager创建cache的bean时传入cachename
 string getname();

 // 获取实际使用的缓存,如:redistemplate、com.github.benmanes.caffeine.cache.cache<object, object>。暂时没发现实际用处,可能只是提供获取原生缓存的bean,以便需要扩展一些缓存操作或统计之类的东西
 object getnativecache();

 // 通过key获取缓存值,注意返回的是valuewrapper,为了兼容存储空值的情况,将返回值包装了一层,通过get方法获取实际值
 valuewrapper get(object key);

 // 通过key获取缓存值,返回的是实际值,即方法的返回值类型
 <t> t get(object key, class<t> type);

 // 通过key获取缓存值,可以使用valueloader.call()来调使用@cacheable注解的方法。当@cacheable注解的sync属性配置为true时使用此方法。因此方法内需要保证回源到数据库的同步性。避免在缓存失效时大量请求回源到数据库
 <t> t get(object key, callable<t> valueloader);

 // 将@cacheable注解方法返回的数据放入缓存中
 void put(object key, object value);

 // 当缓存中不存在key时才放入缓存。返回值是当key存在时原有的数据
 valuewrapper putifabsent(object key, object value);

 // 删除缓存
 void evict(object key);

 // 删除缓存中的所有数据。需要注意的是,具体实现中只删除使用@cacheable注解缓存的所有数据,不要影响应用内的其他缓存
 void clear();

 // 缓存返回值的包装
 interface valuewrapper {

 // 返回实际缓存的对象
 object get();
 }

 // 当{@link #get(object, callable)}抛出异常时,会包装成此异常抛出
 @suppresswarnings("serial")
 class valueretrievalexception extends runtimeexception {

 private final object key;

 public valueretrievalexception(object key, callable<?> loader, throwable ex) {
  super(string.format("value for key '%s' could not be loaded using '%s'", key, loader), ex);
  this.key = key;
 }

 public object getkey() {
  return this.key;
 }
 }
}

cachemanager接口

主要提供cache实现bean的创建,每个应用里可以通过cachename来对cache进行隔离,每个cachename对应一个cache实现。spring框架中默认提供的实现与cache的实现都是成对出现,包结构也在上图中

#cachemanager.java

package org.springframework.cache;

import java.util.collection;

public interface cachemanager {

 // 通过cachename创建cache的实现bean,具体实现中需要存储已创建的cache实现bean,避免重复创建,也避免内存缓存对象(如caffeine)重新创建后原来缓存内容丢失的情况
 cache getcache(string name);

 // 返回所有的cachename
 collection<string> getcachenames();
}

常用注解说明

@cacheable:主要应用到查询数据的方法上

package org.springframework.cache.annotation;
import java.lang.annotation.documented;
import java.lang.annotation.elementtype;
import java.lang.annotation.inherited;
import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
import java.lang.annotation.target;
import java.util.concurrent.callable;
import org.springframework.core.annotation.aliasfor;
@target({elementtype.method, elementtype.type})
@retention(retentionpolicy.runtime)
@inherited
@documented
public @interface cacheable {
    // cachenames,cachemanager就是通过这个名称创建对应的cache实现bean
 @aliasfor("cachenames")
 string[] value() default {};

 @aliasfor("value")
 string[] cachenames() default {};

    // 缓存的key,支持spel表达式。默认是使用所有参数及其计算的hashcode包装后的对象(simplekey)
 string key() default "";

 // 缓存key生成器,默认实现是simplekeygenerator
 string keygenerator() default "";

 // 指定使用哪个cachemanager
 string cachemanager() default "";

 // 缓存解析器
 string cacheresolver() default "";

 // 缓存的条件,支持spel表达式,当达到满足的条件时才缓存数据。在调用方法前后都会判断
 string condition() default "";
    
    // 满足条件时不更新缓存,支持spel表达式,只在调用方法后判断
 string unless() default "";

 // 回源到实际方法获取数据时,是否要保持同步,如果为false,调用的是cache.get(key)方法;如果为true,调用的是cache.get(key, callable)方法
 boolean sync() default false;
}

@cacheevict:清除缓存,主要应用到删除数据的方法上。相比cacheable多了两个属性

package org.springframework.cache.annotation;
import java.lang.annotation.documented;
import java.lang.annotation.elementtype;
import java.lang.annotation.inherited;
import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
import java.lang.annotation.target;
import org.springframework.core.annotation.aliasfor;
@target({elementtype.method, elementtype.type})
@retention(retentionpolicy.runtime)
@inherited
@documented
public @interface cacheevict {
    // ...相同属性说明请参考@cacheable中的说明

 // 是否要清除所有缓存的数据,为false时调用的是cache.evict(key)方法;为true时调用的是cache.clear()方法
 boolean allentries() default false;

 // 调用方法之前或之后清除缓存
 boolean beforeinvocation() default false;
}

  1. @cacheput:放入缓存,主要用到对数据有更新的方法上。属性说明参考@cacheable
  2. @caching:用于在一个方法上配置多种注解
  3. @enablecaching:启用spring cache缓存,作为总的开关,在spring boot的启动类或配置类上需要加上此注解才会生效

spring boot + spring cache

spring boot中已经整合了spring cache,并且提供了多种缓存的配置,在使用时只需要配置使用哪个缓存(enum cachetype)即可。

spring boot中多增加了一个可以扩展的东西,就是cachemanagercustomizer接口,可以自定义实现这个接口,然后对cachemanager做一些设置,比如:

package com.itopener.demo.cache.redis.config;

import java.util.map;
import java.util.concurrent.concurrenthashmap;

import org.springframework.boot.autoconfigure.cache.cachemanagercustomizer;
import org.springframework.data.redis.cache.rediscachemanager;

public class rediscachemanagercustomizer implements cachemanagercustomizer<rediscachemanager> {

 @override
 public void customize(rediscachemanager cachemanager) {
 // 默认过期时间,单位秒
 cachemanager.setdefaultexpiration(1000);
 cachemanager.setuseprefix(false);
 map<string, long> expires = new concurrenthashmap<string, long>();
 expires.put("useridcache", 2000l);
 cachemanager.setexpires(expires);
 }

}

加载这个bean:

package com.itopener.demo.cache.redis.config;

import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;

/**
 * @author fuwei.deng
 * @date 2017年12月22日 上午10:24:54
 * @version 1.0.0
 */
@configuration
public class cacheredisconfiguration {
 
 @bean
 public rediscachemanagercustomizer rediscachemanagercustomizer() {
 return new rediscachemanagercustomizer();
 }
}

常用的缓存就是redis了,redis对于spring cache接口的实现是在spring-data-redis包中

这里提下我认为的rediscache实现中的缺陷:

1.在缓存失效的瞬间,如果有线程获取缓存数据,可能出现返回null的情况,原因是rediscache实现中是如下步骤:

  1. 判断缓存key是否存在
  2. 如果key存在,再获取缓存数据,并返回

因此当判断key存在后缓存失效了,再去获取缓存是没有数据的,就返回null了。

2.rediscachemanager中是否允许存储空值的属性(cachenullvalues)默认为false,即不允许存储空值,这样会存在缓存穿透的风险。缺陷是这个属性是final类型的,只能在创建对象是通过构造方法传入,所以要避免缓存穿透就只能自己在应用内声明rediscachemanager这个bean了

3.rediscachemanager中的属性无法通过配置文件直接配置,只能在应用内实现cachemanagercustomizer接口来进行设置,个人认为不太方便

caffeine

caffeine是一个基于google开源的guava设计理念的一个高性能内存缓存,使用java8开发,spring boot引入caffeine后已经逐步废弃guava的整合了。caffeine源码及介绍地址:caffeine

caffeine提供了多种缓存填充策略、值回收策略,同时也包含了缓存命中次数等统计数据,对缓存的优化能够提供很大帮助

caffeine的介绍可以参考:

这里简单说下caffeine基于时间的回收策略有以下几种:

  1. expireafteraccess:访问后到期,从上次读或写发生后的过期时间
  2. expireafterwrite:写入后到期,从上次写入发生之后的过期时间
  3. 自定义策略:到期时间由实现expiry接口后单独计算

spring boot + spring cache 实现两级缓存(redis + caffeine)

本人开头提到了,就算是使用了redis缓存,也会存在一定程度的网络传输上的消耗,在实际应用当中,会存在一些变更频率非常低的数据,就可以直接缓存在应用内部,对于一些实时性要求不太高的数据,也可以在应用内部缓存一定时间,减少对redis的访问,提高响应速度

由于spring-data-redis框架中redis对spring cache的实现有一些不足,在使用起来可能会出现一些问题,所以就不基于原来的实现去扩展了,直接参考实现方式,去实现cache和cachemanager接口

还需要注意一点,一般应用都部署了多个节点,一级缓存是在应用内的缓存,所以当对数据更新和清除时,需要通知所有节点进行清理缓存的操作。可以有多种方式来实现这种效果,比如:zookeeper、mq等,但是既然用了redis缓存,redis本身是有支持订阅/发布功能的,所以就不依赖其他组件了,直接使用redis的通道来通知其他节点进行清理缓存的操作

以下就是对spring boot + spring cache实现两级缓存(redis + caffeine)的starter封装步骤和源码

定义properties配置属性类

package com.itopener.cache.redis.caffeine.spring.boot.autoconfigure;
import java.util.hashmap;
import java.util.hashset;
import java.util.map;
import java.util.set;
import org.springframework.boot.context.properties.configurationproperties;
/** 
 * @author fuwei.deng
 * @date 2018年1月29日 上午11:32:15
 * @version 1.0.0
 */
@configurationproperties(prefix = "spring.cache.multi")
public class cacherediscaffeineproperties { 
 private set<string> cachenames = new hashset<>(); 
 /** 是否存储空值,默认true,防止缓存穿透*/
 private boolean cachenullvalues = true; 
 /** 是否动态根据cachename创建cache的实现,默认true*/
 private boolean dynamic = true;
 
 /** 缓存key的前缀*/
 private string cacheprefix; 
 private redis redis = new redis(); 
 private caffeine caffeine = new caffeine();
 public class redis { 
 /** 全局过期时间,单位毫秒,默认不过期*/
 private long defaultexpiration = 0;
 
 /** 每个cachename的过期时间,单位毫秒,优先级比defaultexpiration高*/
 private map<string, long> expires = new hashmap<>();
 
 /** 缓存更新时通知其他节点的topic名称*/
 private string topic = "cache:redis:caffeine:topic";

 public long getdefaultexpiration() {
  return defaultexpiration;
 }

 public void setdefaultexpiration(long defaultexpiration) {
  this.defaultexpiration = defaultexpiration;
 }

 public map<string, long> getexpires() {
  return expires;
 }

 public void setexpires(map<string, long> expires) {
  this.expires = expires;
 }

 public string gettopic() {
  return topic;
 }

 public void settopic(string topic) {
  this.topic = topic;
 }
 
 }
 
 public class caffeine { 
 /** 访问后过期时间,单位毫秒*/
 private long expireafteraccess;
 
 /** 写入后过期时间,单位毫秒*/
 private long expireafterwrite;
 
 /** 写入后刷新时间,单位毫秒*/
 private long refreshafterwrite;
 
 /** 初始化大小*/
 private int initialcapacity;
 
 /** 最大缓存对象个数,超过此数量时之前放入的缓存将失效*/
 private long maximumsize;
 
 /** 由于权重需要缓存对象来提供,对于使用spring cache这种场景不是很适合,所以暂不支持配置*/
// private long maximumweight;
 
 public long getexpireafteraccess() {
  return expireafteraccess;
 }

 public void setexpireafteraccess(long expireafteraccess) {
  this.expireafteraccess = expireafteraccess;
 }

 public long getexpireafterwrite() {
  return expireafterwrite;
 }

 public void setexpireafterwrite(long expireafterwrite) {
  this.expireafterwrite = expireafterwrite;
 }

 public long getrefreshafterwrite() {
  return refreshafterwrite;
 }

 public void setrefreshafterwrite(long refreshafterwrite) {
  this.refreshafterwrite = refreshafterwrite;
 }

 public int getinitialcapacity() {
  return initialcapacity;
 }

 public void setinitialcapacity(int initialcapacity) {
  this.initialcapacity = initialcapacity;
 }

 public long getmaximumsize() {
  return maximumsize;
 }

 public void setmaximumsize(long maximumsize) {
  this.maximumsize = maximumsize;
 }
 }

 public set<string> getcachenames() {
 return cachenames;
 }

 public void setcachenames(set<string> cachenames) {
 this.cachenames = cachenames;
 }

 public boolean iscachenullvalues() {
 return cachenullvalues;
 }

 public void setcachenullvalues(boolean cachenullvalues) {
 this.cachenullvalues = cachenullvalues;
 }

 public boolean isdynamic() {
 return dynamic;
 }

 public void setdynamic(boolean dynamic) {
 this.dynamic = dynamic;
 }

 public string getcacheprefix() {
 return cacheprefix;
 }

 public void setcacheprefix(string cacheprefix) {
 this.cacheprefix = cacheprefix;
 }

 public redis getredis() {
 return redis;
 }

 public void setredis(redis redis) {
 this.redis = redis;
 }

 public caffeine getcaffeine() {
 return caffeine;
 }

 public void setcaffeine(caffeine caffeine) {
 this.caffeine = caffeine;
 }
}

spring cache中有实现cache接口的一个抽象类abstractvalueadaptingcache,包含了空值的包装和缓存值的包装,所以就不用实现cache接口了,直接实现abstractvalueadaptingcache抽象类

package com.itopener.cache.redis.caffeine.spring.boot.autoconfigure.support;
import java.lang.reflect.constructor;
import java.util.map;
import java.util.set;
import java.util.concurrent.callable;
import java.util.concurrent.timeunit;
import java.util.concurrent.locks.reentrantlock;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.cache.support.abstractvalueadaptingcache;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.util.stringutils;
import com.github.benmanes.caffeine.cache.cache;
import com.itopener.cache.redis.caffeine.spring.boot.autoconfigure.cacherediscaffeineproperties;

/**
 * @author fuwei.deng
 * @date 2018年1月26日 下午5:24:11
 * @version 1.0.0
 */
public class rediscaffeinecache extends abstractvalueadaptingcache { 
 private final logger logger = loggerfactory.getlogger(rediscaffeinecache.class);
 private string name;
 private redistemplate<object, object> redistemplate;
 private cache<object, object> caffeinecache;
 private string cacheprefix;
 private long defaultexpiration = 0;
 private map<string, long> expires;
 private string topic = "cache:redis:caffeine:topic"; 
 protected rediscaffeinecache(boolean allownullvalues) {
 super(allownullvalues);
 }
 
 public rediscaffeinecache(string name, redistemplate<object, object> redistemplate, cache<object, object> caffeinecache, cacherediscaffeineproperties cacherediscaffeineproperties) {
 super(cacherediscaffeineproperties.iscachenullvalues());
 this.name = name;
 this.redistemplate = redistemplate;
 this.caffeinecache = caffeinecache;
 this.cacheprefix = cacherediscaffeineproperties.getcacheprefix();
 this.defaultexpiration = cacherediscaffeineproperties.getredis().getdefaultexpiration();
 this.expires = cacherediscaffeineproperties.getredis().getexpires();
 this.topic = cacherediscaffeineproperties.getredis().gettopic();
 }

 @override
 public string getname() {
 return this.name;
 }

 @override
 public object getnativecache() {
 return this;
 }

 @suppresswarnings("unchecked")
 @override
 public <t> t get(object key, callable<t> valueloader) {
 object value = lookup(key);
 if(value != null) {
  return (t) value;
 }
 
 reentrantlock lock = new reentrantlock();
 try {
  lock.lock();
  value = lookup(key);
  if(value != null) {
  return (t) value;
  }
  value = valueloader.call();
  object storevalue = tostorevalue(valueloader.call());
  put(key, storevalue);
  return (t) value;
 } catch (exception e) {
  try {
        class<?> c = class.forname("org.springframework.cache.cache$valueretrievalexception");
        constructor<?> constructor = c.getconstructor(object.class, callable.class, throwable.class);
        runtimeexception exception = (runtimeexception) constructor.newinstance(key, valueloader, e.getcause());
        throw exception;        
      } catch (exception e1) {
        throw new illegalstateexception(e1);
      }
 } finally {
  lock.unlock();
 }
 }

 @override
 public void put(object key, object value) {
 if (!super.isallownullvalues() && value == null) {
  this.evict(key);
      return;
    }
 long expire = getexpire();
 if(expire > 0) {
  redistemplate.opsforvalue().set(getkey(key), tostorevalue(value), expire, timeunit.milliseconds);
 } else {
  redistemplate.opsforvalue().set(getkey(key), tostorevalue(value));
 }
 
 push(new cachemessage(this.name, key));
 
 caffeinecache.put(key, value);
 }

 @override
 public valuewrapper putifabsent(object key, object value) {
 object cachekey = getkey(key);
 object prevvalue = null;
 // 考虑使用分布式锁,或者将redis的setifabsent改为原子性操作
 synchronized (key) {
  prevvalue = redistemplate.opsforvalue().get(cachekey);
  if(prevvalue == null) {
  long expire = getexpire();
  if(expire > 0) {
   redistemplate.opsforvalue().set(getkey(key), tostorevalue(value), expire, timeunit.milliseconds);
  } else {
   redistemplate.opsforvalue().set(getkey(key), tostorevalue(value));
  }
  
  push(new cachemessage(this.name, key));
  
  caffeinecache.put(key, tostorevalue(value));
  }
 }
 return tovaluewrapper(prevvalue);
 }

 @override
 public void evict(object key) {
 // 先清除redis中缓存数据,然后清除caffeine中的缓存,避免短时间内如果先清除caffeine缓存后其他请求会再从redis里加载到caffeine中
 redistemplate.delete(getkey(key));
 
 push(new cachemessage(this.name, key));
 
 caffeinecache.invalidate(key);
 }

 @override
 public void clear() {
 // 先清除redis中缓存数据,然后清除caffeine中的缓存,避免短时间内如果先清除caffeine缓存后其他请求会再从redis里加载到caffeine中
 set<object> keys = redistemplate.keys(this.name.concat(":"));
 for(object key : keys) {
  redistemplate.delete(key);
 }
 
 push(new cachemessage(this.name, null));
 
 caffeinecache.invalidateall();
 }

 @override
 protected object lookup(object key) {
 object cachekey = getkey(key);
 object value = caffeinecache.getifpresent(key);
 if(value != null) {
  logger.debug("get cache from caffeine, the key is : {}", cachekey);
  return value;
 }
 
 value = redistemplate.opsforvalue().get(cachekey);
 
 if(value != null) {
  logger.debug("get cache from redis and put in caffeine, the key is : {}", cachekey);
  caffeinecache.put(key, value);
 }
 return value;
 }

 private object getkey(object key) {
 return this.name.concat(":").concat(stringutils.isempty(cacheprefix) ? key.tostring() : cacheprefix.concat(":").concat(key.tostring()));
 }
 
 private long getexpire() {
 long expire = defaultexpiration;
 long cachenameexpire = expires.get(this.name);
 return cachenameexpire == null ? expire : cachenameexpire.longvalue();
 }
 
 /**
 * @description 缓存变更时通知其他节点清理本地缓存
 * @author fuwei.deng
 * @date 2018年1月31日 下午3:20:28
 * @version 1.0.0
 * @param message
 */
 private void push(cachemessage message) {
 redistemplate.convertandsend(topic, message);
 }
 
 /**
 * @description 清理本地缓存
 * @author fuwei.deng
 * @date 2018年1月31日 下午3:15:39
 * @version 1.0.0
 * @param key
 */
 public void clearlocal(object key) {
 logger.debug("clear local cache, the key is : {}", key);
 if(key == null) {
  caffeinecache.invalidateall();
 } else {
  caffeinecache.invalidate(key);
 }
 }
}

实现cachemanager接口

package com.itopener.cache.redis.caffeine.spring.boot.autoconfigure.support;

import java.util.collection;
import java.util.set;
import java.util.concurrent.concurrenthashmap;
import java.util.concurrent.concurrentmap;
import java.util.concurrent.timeunit;

import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.cache.cache;
import org.springframework.cache.cachemanager;
import org.springframework.data.redis.core.redistemplate;

import com.github.benmanes.caffeine.cache.caffeine;
import com.itopener.cache.redis.caffeine.spring.boot.autoconfigure.cacherediscaffeineproperties;

/**
 * @author fuwei.deng
 * @date 2018年1月26日 下午5:24:52
 * @version 1.0.0
 */
public class rediscaffeinecachemanager implements cachemanager {
 
 private final logger logger = loggerfactory.getlogger(rediscaffeinecachemanager.class);
 
 private concurrentmap<string, cache> cachemap = new concurrenthashmap<string, cache>();
 
 private cacherediscaffeineproperties cacherediscaffeineproperties;
 
 private redistemplate<object, object> redistemplate;

 private boolean dynamic = true;

 private set<string> cachenames;

 public rediscaffeinecachemanager(cacherediscaffeineproperties cacherediscaffeineproperties,
  redistemplate<object, object> redistemplate) {
 super();
 this.cacherediscaffeineproperties = cacherediscaffeineproperties;
 this.redistemplate = redistemplate;
 this.dynamic = cacherediscaffeineproperties.isdynamic();
 this.cachenames = cacherediscaffeineproperties.getcachenames();
 }

 @override
 public cache getcache(string name) {
 cache cache = cachemap.get(name);
 if(cache != null) {
  return cache;
 }
 if(!dynamic && !cachenames.contains(name)) {
  return cache;
 }
 
 cache = new rediscaffeinecache(name, redistemplate, caffeinecache(), cacherediscaffeineproperties);
 cache oldcache = cachemap.putifabsent(name, cache);
 logger.debug("create cache instance, the cache name is : {}", name);
 return oldcache == null ? cache : oldcache;
 }
 
 public com.github.benmanes.caffeine.cache.cache<object, object> caffeinecache(){
 caffeine<object, object> cachebuilder = caffeine.newbuilder();
 if(cacherediscaffeineproperties.getcaffeine().getexpireafteraccess() > 0) {
  cachebuilder.expireafteraccess(cacherediscaffeineproperties.getcaffeine().getexpireafteraccess(), timeunit.milliseconds);
 }
 if(cacherediscaffeineproperties.getcaffeine().getexpireafterwrite() > 0) {
  cachebuilder.expireafterwrite(cacherediscaffeineproperties.getcaffeine().getexpireafterwrite(), timeunit.milliseconds);
 }
 if(cacherediscaffeineproperties.getcaffeine().getinitialcapacity() > 0) {
  cachebuilder.initialcapacity(cacherediscaffeineproperties.getcaffeine().getinitialcapacity());
 }
 if(cacherediscaffeineproperties.getcaffeine().getmaximumsize() > 0) {
  cachebuilder.maximumsize(cacherediscaffeineproperties.getcaffeine().getmaximumsize());
 }
 if(cacherediscaffeineproperties.getcaffeine().getrefreshafterwrite() > 0) {
  cachebuilder.refreshafterwrite(cacherediscaffeineproperties.getcaffeine().getrefreshafterwrite(), timeunit.milliseconds);
 }
 return cachebuilder.build();
 }

 @override
 public collection<string> getcachenames() {
 return this.cachenames;
 }
 
 public void clearlocal(string cachename, object key) {
 cache cache = cachemap.get(cachename);
 if(cache == null) {
  return ;
 }
 
 rediscaffeinecache rediscaffeinecache = (rediscaffeinecache) cache;
 rediscaffeinecache.clearlocal(key);
 }
}

redis消息发布/订阅,传输的消息类

package com.itopener.cache.redis.caffeine.spring.boot.autoconfigure.support;
import java.io.serializable;

/** 
 * @author fuwei.deng
 * @date 2018年1月29日 下午1:31:17
 * @version 1.0.0
 */
public class cachemessage implements serializable {

 /** */
 private static final long serialversionuid = 5987219310442078193l;

 private string cachename; 
 private object key;
 public cachemessage(string cachename, object key) {
 super();
 this.cachename = cachename;
 this.key = key;
 }

 public string getcachename() {
 return cachename;
 }

 public void setcachename(string cachename) {
 this.cachename = cachename;
 }

 public object getkey() {
 return key;
 }

 public void setkey(object key) {
 this.key = key;
 }
}

监听redis消息需要实现messagelistener接口

package com.itopener.cache.redis.caffeine.spring.boot.autoconfigure.support;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.data.redis.connection.message;
import org.springframework.data.redis.connection.messagelistener;
import org.springframework.data.redis.core.redistemplate;
/** 
 * @author fuwei.deng
 * @date 2018年1月30日 下午5:22:33
 * @version 1.0.0
 */
public class cachemessagelistener implements messagelistener { 
 private final logger logger = loggerfactory.getlogger(cachemessagelistener.class);
 private redistemplate<object, object> redistemplate;
 private rediscaffeinecachemanager rediscaffeinecachemanager;
 public cachemessagelistener(redistemplate<object, object> redistemplate,
  rediscaffeinecachemanager rediscaffeinecachemanager) {
 super();
 this.redistemplate = redistemplate;
 this.rediscaffeinecachemanager = rediscaffeinecachemanager;
 }

 @override
 public void onmessage(message message, byte[] pattern) {
 cachemessage cachemessage = (cachemessage) redistemplate.getvalueserializer().deserialize(message.getbody());
 logger.debug("recevice a redis topic message, clear local cache, the cachename is {}, the key is {}", cachemessage.getcachename(), cachemessage.getkey());
 rediscaffeinecachemanager.clearlocal(cachemessage.getcachename(), cachemessage.getkey());
 }
}

增加spring boot配置类

package com.itopener.cache.redis.caffeine.spring.boot.autoconfigure;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.autoconfigure.autoconfigureafter;
import org.springframework.boot.autoconfigure.condition.conditionalonbean;
import org.springframework.boot.autoconfigure.data.redis.redisautoconfiguration;
import org.springframework.boot.context.properties.enableconfigurationproperties;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.data.redis.listener.channeltopic;
import org.springframework.data.redis.listener.redismessagelistenercontainer;
import com.itopener.cache.redis.caffeine.spring.boot.autoconfigure.support.cachemessagelistener;
import com.itopener.cache.redis.caffeine.spring.boot.autoconfigure.support.rediscaffeinecachemanager;
/** 
 * @author fuwei.deng
 * @date 2018年1月26日 下午5:23:03
 * @version 1.0.0
 */
@configuration
@autoconfigureafter(redisautoconfiguration.class)
@enableconfigurationproperties(cacherediscaffeineproperties.class)
public class cacherediscaffeineautoconfiguration {
 
 @autowired
 private cacherediscaffeineproperties cacherediscaffeineproperties;
 
 @bean
 @conditionalonbean(redistemplate.class)
 public rediscaffeinecachemanager cachemanager(redistemplate<object, object> redistemplate) {
 return new rediscaffeinecachemanager(cacherediscaffeineproperties, redistemplate);
 }
 
 @bean
 public redismessagelistenercontainer redismessagelistenercontainer(redistemplate<object, object> redistemplate, 
  rediscaffeinecachemanager rediscaffeinecachemanager) {
 redismessagelistenercontainer redismessagelistenercontainer = new redismessagelistenercontainer();
 redismessagelistenercontainer.setconnectionfactory(redistemplate.getconnectionfactory());
 cachemessagelistener cachemessagelistener = new cachemessagelistener(redistemplate, rediscaffeinecachemanager);
 redismessagelistenercontainer.addmessagelistener(cachemessagelistener, new channeltopic(cacherediscaffeineproperties.getredis().gettopic()));
 return redismessagelistenercontainer;
 }
}

在resources/meta-inf/spring.factories文件中增加spring boot配置扫描

# auto configure
org.springframework.boot.autoconfigure.enableautoconfiguration=\
com.itopener.cache.redis.caffeine.spring.boot.autoconfigure.cacherediscaffeineautoconfiguration

接下来就可以使用maven引入使用了

<dependency>
  <groupid>com.itopener</groupid>
  <artifactid>cache-redis-caffeine-spring-boot-starter</artifactid>
  <version>1.0.0-snapshot</version>
  <type>pom</type>
</dependency>

在启动类上增加@enablecaching注解,在需要缓存的方法上增加@cacheable注解

package com.itopener.demo.cache.redis.caffeine.service;
import java.util.random;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.cache.annotation.cacheevict;
import org.springframework.cache.annotation.cacheput;
import org.springframework.cache.annotation.cacheable;
import org.springframework.stereotype.service;
import com.itopener.demo.cache.redis.caffeine.vo.uservo;
import com.itopener.utils.timestamputil;

@service
public class cacherediscaffeineservice {
 
 private final logger logger = loggerfactory.getlogger(cacherediscaffeineservice.class);

 @cacheable(key = "'cache_user_id_' + #id", value = "useridcache", cachemanager = "cachemanager")
 public uservo get(long id) {
 logger.info("get by id from db");
 uservo user = new uservo();
 user.setid(id);
 user.setname("name" + id);
 user.setcreatetime(timestamputil.current());
 return user;
 }
 
 @cacheable(key = "'cache_user_name_' + #name", value = "usernamecache", cachemanager = "cachemanager")
 public uservo get(string name) {
 logger.info("get by name from db");
 uservo user = new uservo();
 user.setid(new random().nextlong());
 user.setname(name);
 user.setcreatetime(timestamputil.current());
 return user;
 }
 
 @cacheput(key = "'cache_user_id_' + #uservo.id", value = "useridcache", cachemanager = "cachemanager")
 public uservo update(uservo uservo) {
 logger.info("update to db");
 uservo.setcreatetime(timestamputil.current());
 return uservo;
 }
 
 @cacheevict(key = "'cache_user_id_' + #id", value = "useridcache", cachemanager = "cachemanager")
 public void delete(long id) {
 logger.info("delete from db");
 }
}

properties文件中redis的配置跟使用redis是一样的,可以增加两级缓存的配置

#两级缓存的配置
spring.cache.multi.caffeine.expireafteraccess=5000
spring.cache.multi.redis.defaultexpiration=60000

#spring cache配置
spring.cache.cache-names=useridcache,usernamecache

#redis配置
#spring.redis.timeout=10000
#spring.redis.password=redispwd
#redis pool
#spring.redis.pool.maxidle=10
#spring.redis.pool.minidle=2
#spring.redis.pool.maxactive=10
#spring.redis.pool.maxwait=3000
#redis cluster
spring.redis.cluster.nodes=127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003,127.0.0.1:7004,127.0.0.1:7005,127.0.0.1:7006
spring.redis.cluster.maxredirects=3

扩展

个人认为redisson的封装更方便一些

  1. 对于spring cache缓存的实现没有那么多的缺陷
  2. 使用redis的hash结构,可以针对不同的hashkey设置过期时间,清理的时候会更方便
  3. 如果基于redisson来实现多级缓存,可以继承redissoncache,在对应方法增加一级缓存的操作即可
  4. 如果有使用分布式锁的情况就更方便了,可以直接使用redisson中封装的分布式锁
  5. redisson中的发布订阅封装得更好用

后续可以增加对于缓存命中率的统计endpoint,这样就可以更好的监控各个缓存的命中情况,以便对缓存配置进行优化

starter目录:springboot / itopener-parent / spring-boot-starters-parent / cache-redis-caffeine-spring-boot-starter-parent

示例代码目录: springboot / itopener-parent / demo-parent / demo-cache-redis-caffeine

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网