一、spring cache是什么?
它利用了aop,实现了基于注解的缓存功能,并且进行了合理的抽象,业务代码不用关心底层是使用了什么缓存框架,只需要简单地加一个注解,就能实现缓存功能了。
而且spring cache也提供了很多默认的配置,用户可以3秒钟就使用上一个很不错的缓存功能。
工作流程:
- 使用spring cache分为很简单的三步:添加依赖(springboot依赖包内置),开启缓存,加缓存注解。
 - 每次调用该方法时,都会检查缓存以查看调用是否已经运行并且不必重复。虽然在大多数情况下,只声明了一个缓存,但注释允许指定多个名称,以便使用多个缓存。在这种情况下,在调用该方法之前检查每个缓存 - 如果至少命中一个缓存,则返回关联的值。
 - 会触发一个后置处理,这会扫描每一个spring bean,查看是否已经存在缓存。如果找到了,就会自动创建一个代理拦截方法调用,使用缓存的bean执行处理。
 
特性:
- 缓存数据是存在redis
 - 默认永不过期
 - key-value键、值队存储
 
二、使用步骤
开启基于注解的缓存
- 在启动类添加以下注解
 
@enablecaching
配置缓存
- 在需要缓存数据的方法上面添加
@cacheable注解,即可缓存这个方法的返回值。 
	@cacheable(value = "defaultkeytest", keygenerator = "simplekeygenerator", /*cachenames = api_detail_key_prefix, key = "target.redisapidetailkeyprefix + ':' + #appcode",*/ unless = "#result == null")
    public openapidetailvo findbyappcode(string appcode) {
        return openapiauthservice.querydetail(appcode);
    }
三、解决方案
方案一:通过编写config设置缓存相关项
- 要指定 key 的过期时间,只需要getrediscacheconfigurationmap方法中添加就可以。
 
@configuration
public class rediscacheconfig {
    @bean
    public keygenerator simplekeygenerator() {
        return (o, method, objects) -> {
            stringbuilder stringbuilder = new stringbuilder();
            stringbuilder.append(o.getclass().getsimplename());
            stringbuilder.append(".");
            stringbuilder.append(method.getname());
            stringbuilder.append("[");
            for (object obj : objects) {
                stringbuilder.append(obj.tostring());
            }
            stringbuilder.append("]");
            return stringbuilder.tostring();
        };
    }
    @bean
    public cachemanager cachemanager(redisconnectionfactory redisconnectionfactory) {
        return new rediscachemanager(
                rediscachewriter.nonlockingrediscachewriter(redisconnectionfactory),
                this.getrediscacheconfigurationwithttl(600), // 默认策略,未配置的 key 会使用这个
                this.getrediscacheconfigurationmap() // 指定 key 策略
        );
    }
    private map<string, rediscacheconfiguration> getrediscacheconfigurationmap() {
        map<string, rediscacheconfiguration> rediscacheconfigurationmap = new hashmap<>();
        rediscacheconfigurationmap.put("userinfolist", this.getrediscacheconfigurationwithttl(3000));
        rediscacheconfigurationmap.put("userinfolistanother", this.getrediscacheconfigurationwithttl(18000));
        return rediscacheconfigurationmap;
    }
    private rediscacheconfiguration getrediscacheconfigurationwithttl(integer seconds) {
        jackson2jsonredisserializer<object> jackson2jsonredisserializer = new jackson2jsonredisserializer<>(object.class);
        objectmapper om = new objectmapper();
        om.setvisibility(propertyaccessor.all, jsonautodetect.visibility.any);
        om.activatedefaulttyping(laissezfairesubtypevalidator.instance,
                objectmapper.defaulttyping.non_final,
                jsontypeinfo.as.wrapper_array);
        jackson2jsonredisserializer.setobjectmapper(om);
        rediscacheconfiguration rediscacheconfiguration = rediscacheconfiguration.defaultcacheconfig();
        rediscacheconfiguration = rediscacheconfiguration.serializevalueswith(
                redisserializationcontext
                        .serializationpair
                        .fromserializer(jackson2jsonredisserializer)
        ).entryttl(duration.ofseconds(seconds));
        return rediscacheconfiguration;
    }
}
- 下面给出三种案例
 
	// 3000秒
    @cacheable(value = "userinfolist", keygenerator = "simplekeygenerator")
    // 18000秒
    @cacheable(value = "userinfolistanother", keygenerator = "simplekeygenerator")
    // 600秒,未指定的key,使用默认策略
    @cacheable(value = "defaultkeytest", keygenerator = "simplekeygenerator")
方案二:通过配置文件
spring:
  # maximumsize:配置缓存的最大条数,当快要达到容量上限的时候,缓存管理器会根据一定的策略将部分缓存项移除。
  # expireafteraccess:配置缓存项的过期机制,缓存项固定30秒将会过期,从而被移除。
  cache:
    caffeine:
      spec: maximumsize=500, expireafteraccess=30s
    type: caffeine
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
            
                                            
                                            
                                            
                                            
                                            
                                            
发表评论