缓存作为提升应用性能的重要手段,其管理策略的合理性直接影响到应用的响应速度和数据一致性。在spring框架中,spring cache提供了一种声明式缓存的解决方案,而redis作为高性能的缓存数据库,被广泛应用于缓存实现。本文将介绍一种通过自定义注解实现spring cache与redis缓存过期时间管理及自动刷新的策略。
1、自定义注解cacheexpireconfig
为了更灵活地控制缓存的过期时间,我们定义了一个名为cacheexpireconfig
的自定义注解。此注解支持在方法级别配置缓存的过期时间和自动刷新时间。
import java.lang.annotation.*; /** * @author tangzx */ @target({elementtype.type, elementtype.method}) @retention(retentionpolicy.runtime) @inherited @documented public @interface cacheexpireconfig { /** * 缓存过期时间,支持单位天(d)、小时(h)、分钟(m)、秒钟(s)(不填单位默认秒) * 例:2h */ string expiretime() default ""; /** * 缓存过期刷新时间,支持单位天(d)、小时(h)、分钟(m)、秒钟(s)(不填单位默认秒) * 例:2h */ string expirerefreshtime() default ""; }
2、使用注解
在spring的@cacheable
注解基础上,通过@cacheexpireconfig
注解,我们可以轻松地为特定方法设置缓存过期和刷新策略。
@override @cacheexpireconfig(expiretime = "60s", expirerefreshtime = "30s") @cacheable(value = "testcache", condition = "#userid != null && #username == null ") public string testcache(string userid, string username) { system.out.println("=====================>"); return "success"; }
3、启动时加载缓存过期配置
在spring boot应用启动时,通过tarediscacheconfiglistener
监听器,扫描所有类和方法,加载带有@cacheexpireconfig
注解的方法的缓存过期配置。
import cn.hutool.core.lang.classscanner; import org.apache.commons.lang3.arrayutils; import org.springframework.boot.context.event.applicationpreparedevent; import org.springframework.cache.annotation.cacheable; import org.springframework.context.applicationlistener; import java.lang.reflect.method; import java.util.set; /** * @author tangzx * @date 2022/12/17 11:05 */ public class tarediscacheconfiglistener implements applicationlistener<applicationpreparedevent> { @override public void onapplicationevent(applicationpreparedevent applicationpreparedevent) { // 扫描所有类 set<class<?>> classes = scanpackage(); for (class<?> target : classes) { method[] methods = target.getmethods(); for (method method : methods) { // 如果方法上未同时注解@cacheable和@cacheexpireconfig,不需要配置 if (!method.isannotationpresent(cacheable.class) || !method.isannotationpresent(cacheexpireconfig.class)) { continue; } cacheable cacheable = method.getannotation(cacheable.class); cacheexpireconfig cacheexpireconfig = method.getannotation(cacheexpireconfig.class); string expiretime = cacheexpireconfig.expiretime(); string expirerefreshtime = cacheexpireconfig.expirerefreshtime(); string[] cachenames = arrayutils.addall(cacheable.cachenames(), cacheable.value()); boolean autorefresh = cacheexpireconfig.autorefresh(); for (string cachename : cachenames) { methodcacheexpireconfig methodcacheexpireconfig = methodcacheexpireconfig.builder() .expiretime(durationutils.parseduration(expiretime).getseconds()) .expirerefreshtime(durationutils.parseduration(expirerefreshtime).getseconds()) .autorefresh(autorefresh) .target(target) .method(method) .build(); tarediscachefactory.addcacheexpireconfig(cachename, methodcacheexpireconfig); } } } } private set<class<?>> scanpackage() { // 使用的hutool的类扫描器,如果项目中未使用工具类,可自行实现 return classscanner.scanpackage(); } }
public static void main(string[] args) { springapplication application = new springapplicationbuilder().sources(startapplication.class).build(args); try { application.addlisteners(new tarediscacheconfiglistener()); application.run(args); } catch (exception e) { e.printstacktrace(); } }
4、重写rediscachemanager,设置过期时间
通过重写rediscachemanager
,我们可以根据配置动态设置每个缓存的过期时间。
import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.data.redis.cache.rediscache; import org.springframework.data.redis.cache.rediscacheconfiguration; import org.springframework.data.redis.cache.rediscachemanager; import org.springframework.data.redis.cache.rediscachewriter; import org.springframework.lang.nullable; import org.springframework.util.assert; import java.time.duration; import java.util.map; /** * @author tzx * @date 2022/12/13 19:33 */ public class tarediscachemanager extends rediscachemanager { private static final logger logger = loggerfactory.getlogger(tarediscachemanager.class); public tarediscachemanager(rediscachewriter cachewriter, rediscacheconfiguration defaultcacheconfiguration) { super(cachewriter, defaultcacheconfiguration); } public tarediscachemanager(rediscachewriter cachewriter, rediscacheconfiguration defaultcacheconfiguration, string... initialcachenames) { super(cachewriter, defaultcacheconfiguration, initialcachenames); } public tarediscachemanager(rediscachewriter cachewriter, rediscacheconfiguration defaultcacheconfiguration, boolean allowinflightcachecreation, string... initialcachenames) { super(cachewriter, defaultcacheconfiguration, allowinflightcachecreation, initialcachenames); } public tarediscachemanager(rediscachewriter cachewriter, rediscacheconfiguration defaultcacheconfiguration, map<string, rediscacheconfiguration> initialcacheconfigurations) { super(cachewriter, defaultcacheconfiguration, initialcacheconfigurations); } public tarediscachemanager(rediscachewriter cachewriter, rediscacheconfiguration defaultcacheconfiguration, map<string, rediscacheconfiguration> initialcacheconfigurations, boolean allowinflightcachecreation) { super(cachewriter, defaultcacheconfiguration, initialcacheconfigurations, allowinflightcachecreation); } @override protected rediscache createrediscache(string name, @nullable rediscacheconfiguration cacheconfig) { methodcacheexpireconfig cacheable = tarediscachefactory.getcacheexpireconfig(name); if (null != cacheable && cacheable.getexpiretime() > 0) { cacheconfig = entryttl(name, cacheable.getexpiretime(), cacheconfig); } return super.createrediscache(name, cacheconfig); } private rediscacheconfiguration entryttl(string cachename, long ttl, @nullable rediscacheconfiguration cacheconfig) { assert.notnull(cacheconfig, "rediscacheconfiguration is required; it must not be null"); cacheconfig = cacheconfig.entryttl(duration.ofseconds(ttl)); if (logger.isdebugenabled()) { logger.debug("rediscache {} 过期时间为{}秒", cachename, ttl); } return cacheconfig; } }
5、缓存自动刷新
在rediscache
的get
方法中,如果缓存未过期,检查是否需要进行自动刷新。
@override public valuewrapper get(@nullable object o) { if (null == o) { return null; } valuewrapper wrapper = this.cache.get(o); // 刷新缓存 if (null != wrapper) { springcontextutil.getapplicationcontext().getbean(tarediscachefactory.class).refreshcache(getname(),o.tostring(), this::put); } return wrapper; }
6、tarediscachefactory刷新策略
tarediscachefactory
负责缓存的刷新逻辑,确保缓存数据的实时性。
import com.alibaba.fastjson.json; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.aop.framework.aopproxyutils; import org.springframework.util.methodinvoker; import java.lang.reflect.invocationtargetexception; import java.lang.reflect.method; import java.util.concurrent.concurrenthashmap; import java.util.concurrent.timeunit; /** * @author tangzx * @date 2022/12/17 11:09 */ public class tarediscachefactory { /** * 缓存过期配置 */ private static final concurrenthashmap<string, methodcacheexpireconfig> cache_expire_config = new concurrenthashmap<>(); private static final logger logger = loggerfactory.getlogger(tarediscachefactory.class); public tarediscachefactory() { // document why this method is empty } public static void addcacheexpireconfig(string cachename, methodcacheexpireconfig methodcacheexpireconfig) { cache_expire_config.put(cachename, methodcacheexpireconfig); } public static methodcacheexpireconfig getcacheexpireconfig(string cachename) { return cache_expire_config.get(cachename); } /** * 刷新缓存 * * @param cachename 缓存名称 * @param cachekey 缓存key */ public void refreshcache(string cachename, string cachekey, refreshcachefunction f) { methodcacheexpireconfig cacheable = getcacheexpireconfig(cachename); if (null == cacheable) { return; } class<?> targetclass = cacheable.gettarget(); method method = cacheable.getmethod(); long expirerefreshtime = cacheable.getexpirerefreshtime(); string rediskey = cachename + cachekey; long expire = redisutil.keyops.getexpire(rediskey); if (expire > expirerefreshtime) { return; } string argsstr = cachekey.split("\\^")[1]; object[] args = json.parseobject(argsstr, object[].class); if (null == args) { return; } try { // 创建方法执行器 methodinvoker methodinvoker = new methodinvoker(); methodinvoker.setarguments(args); methodinvoker.settargetclass(targetclass); methodinvoker.settargetmethod(method.getname()); methodinvoker.settargetobject(aopproxyutils.getsingletontarget(springcontextutil.getapplicationcontext().getbean(targetclass))); methodinvoker.prepare(); object invoke = methodinvoker.invoke(); //然后设置进缓存和重新设置过期时间 f.put(cachekey, invoke); redisutil.keyops.expire(cachekey, cacheable.getexpiretime(), timeunit.seconds); } catch (invocationtargetexception | illegalaccessexception | nosuchmethodexception | classnotfoundexception e) { logger.error("刷新缓存失败:" + e.getmessage(), e); } } }
7、methodcacheexpireconfig
import lombok.builder; import lombok.data; import java.lang.reflect.method; /** * @author tzx * @date 2022/12/17 11:10 */ @data @builder public class methodcacheexpireconfig { /** * 缓存过期时间 */ private long expiretime; /** * 缓存过期自动刷新阈值 */ private long expirerefreshtime; /** * 是否自动刷新 */ private boolean autorefresh; /** * 类对象 */ private class<?> target; /** * 缓存方法 */ private method method; }
8、refreshcachefunction
/** * @author tangzx */ @functionalinterface public interface refreshcachefunction { /** * 缓存put * * @param key key * @param value value */ void put(string key, object value); }
9、durationutils
import java.time.duration; /** * @author tzx * @date 2022/12/17 12:04 */ public class durationutils { private durationutils(){ // 2022/12/18 } public static duration parseduration(string ttlstr) { string timeunit = ttlstr.substring(ttlstr.length() - 1); switch (timeunit) { case "d": return duration.ofdays(parselong(ttlstr)); case "h": return duration.ofhours(parselong(ttlstr)); case "m": return duration.ofminutes(parselong(ttlstr)); case "s": return duration.ofseconds(parselong(ttlstr)); default: return duration.ofseconds(long.parselong(ttlstr)); } } private static long parselong(string ttlstr) { return long.parselong(ttlstr.substring(0, ttlstr.length() - 1)); } }
到此这篇关于spirngcache、redis指定过期时间、到期自动刷新的文章就介绍到这了,更多相关spirngcache、redis指定过期时间 内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论