注解
package com.olivia.sdk.ann;
import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;
/***
*
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RedissonCacheAnn {
//组名称(user:info)
String group() default "";
//SpelExpression表达式的key,已#开头,单个字段#userId,对象中的字段#dto.userId
String key();
//超时时间单位(默认秒)
TimeUnit unit() default TimeUnit.SECONDS;
//超时时间-默认1个小时
long ttl() default 3600L;
}
实现类
package com.olivia.sdk.aspect;
import com.olivia.sdk.ann.RedissonCacheAnn;
import com.olivia.sdk.utils.SpelUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Slf4j
@Aspect
@Component
public class RedisCacheSetAspect {
@Resource
RedisTemplate<String, Object> redisTemplate;
@Pointcut("@annotation(com.olivia.sdk.ann.RedissonCacheAnn)")
public void aspect() {
}
@Around("aspect()")
public Object around(ProceedingJoinPoint point) throws Throwable {
String methodName = point.getSignature().getName();
Class<?> classTarget = point.getTarget().getClass();
Class<?>[] par = ((MethodSignature) point.getSignature()).getParameterTypes();
Method objMethod = classTarget.getMethod(methodName, par);
//判断返回值,如果是void则直接返回处理结果
if (objMethod.getReturnType().equals(Void.TYPE)) {
log.warn("@CacheSet method={} use CachePut but has no return value.", methodName);
return point.proceed(point.getArgs());
}
String key = null;
RedissonCacheAnn cacheAnn = objMethod.getAnnotation(RedissonCacheAnn.class);
Object result = null;
String tmKey = cacheAnn.key();
if (StringUtils.isNotBlank(tmKey) && tmKey.startsWith("#")) {
tmKey = SpelUtils.parseKey(cacheAnn.key(), objMethod, point.getArgs());
}
key = "cache:" + cacheAnn.group() + ":" + tmKey;
if (log.isDebugEnabled()) log.debug("RedissonCacheAnn {} key {}", methodName, key);
try {
Object cacheValue = redisTemplate.opsForValue().get(key);
if (cacheValue != null) {
if (log.isDebugEnabled()) {
if (log.isDebugEnabled()) log.debug("RedissonCacheAnn {} value: {}", methodName, cacheValue);
}
//存在缓存数据,返回数据
return cacheValue;
}
} catch (Exception e) {
log.error("RedissonCacheAnn {} get error: {}", methodName, e.getMessage());
}
//缓存中无数据时初始化缓存值
result = point.proceed();
try {
redisTemplate.opsForValue().set(key, result, cacheAnn.ttl(), cacheAnn.unit());
} catch (Exception e) {
log.error("RedissonCacheAnn {} set error: {}", methodName, e.getMessage());
}
return result;
}
}