spring boot集成redis进行数据缓存功能
@Cacheable 表明Spring在调用方法之前,首先应该在缓存中查找方法的返回值。如果这个值能够找到,就会返回缓存的值。否则的话,这个方法就会被调用,返回值会放到缓存之中
@cacheput 表明Spring应该将方法的返回值放到缓存中。在方法的调用前并不会 检查缓存,方法始终都会被调用
@cacheevict 表明Spring应该在缓存中清除一个或多个条目
@caching 这是一个分组的注解,能够同时应用多个其他的缓存注解
@cacheconfig 可以在类层级配置一些共用的缓存配置
当然,spring已经封装非常好了,我在之前实现了一个注解式redis缓存,整体来说可用性还是不错的,先分享出来,有时间在把springboot缓存整合
/** * @liuxl */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD,ElementType.TYPE}) @Documented public @interface RedisCache { /** * @Description: 如果name不为空,则以name为key,若name为空,则以类名:方法名为key * @Param: * @return: */ String key(); /** * @Description: 数据缓存时间单位s秒 * @Param: 默认10分钟 * @return: */ int cacheTime() default 600; }
import com.alibaba.fastjson.JSON; import java.lang.reflect.Method; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * @author liuxl */ @Aspect @Component @Order(-9) public class RedisCacheAspect { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Around("@annotation(cache)") public Object redisCache(ProceedingJoinPoint pjp,RedisCache cache) throws Throwable { String redisResult = ""; String className = pjp.getTarget().getClass().getName(); Signature signature = pjp.getSignature(); if(!(signature instanceof MethodSignature)){ throw new IllegalArgumentException(); } MethodSignature methodSignature = (MethodSignature) signature; String methodName = pjp.getSignature().getName(); Method method = pjp.getTarget().getClass().getMethod(methodSignature.getName(),methodSignature.getParameterTypes()); String dictName=method.getAnnotation(RedisCache.class).key(); String key = StringUtils.isNotBlank(dictName)?dictName:genKey(className,methodName); logger.info("生成的key[{}]",key); Object[] args = pjp.getArgs(); int cacheTime = method.getAnnotation(RedisCache.class).cacheTime(); Object result = null; if(RedisUtils.size(key)==0L) { logger.info("缓存未命中key=[{}]",key); result = pjp.proceed(args); redisResult = JSON.toJSONString(result); RedisUtils.set(key,redisResult,cacheTime); } else{ //缓存命中 logger.info("缓存命中key=[{}]",key); redisResult = RedisUtils.get(key); //得到被代理方法的返回值类型 Class returnType = method.getReturnType(); result = JSON.parseObject(redisResult,returnType); } return result; } /** * @Description: 生成key * @Param: */ private String genKey(String className, String methodName) { return StringUtils.substringAfterLast(className,".").concat(methodName); } }