自定义注解
package com.edu.shengda.common.cache;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({
ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface GmallCache{
String prefix() default "cache";
}
处理环绕通知
package com.edu.shengda.common.cache;
import com.alibaba.fastjson.JSON;
import com.edu.shengda.common.constant.RedisConst;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
@Component
@Aspect
public class GmallCacheAspect {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private RedissonClient redissonClient;
@Around("@annotation(com.edu.shengda.common.cache.GmallCache)")
public Object cacheAroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
Object object = new Object();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
GmallCache gmallCache = signature.getMethod().getAnnotation(GmallCache.class);
String prefix = gmallCache.prefix();
Object[] args = joinPoint.getArgs();
String key = prefix + args.toString();
try {
Object o = cacheHit(signature, key);
if (o == null) {
String lockKey = prefix + ":lock";
RLock lock = redissonClient.getLock(lockKey);
boolean tryLock = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
if (tryLock) {
try {
object = joinPoint.proceed(joinPoint.getArgs());
if (object == null) {
Object object1 = new Object();
redisTemplate.opsForValue().set(key, JSON.toJSONString(object1), RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
return object1;
}
redisTemplate.opsForValue().set(key, JSON.toJSONString(object), RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);
return object;
} catch (Throwable throwable) {
throwable.printStackTrace();
} finally {
lock.unlock();
}
} else {
Thread.sleep(1000);
return cacheAroundAdvice(joinPoint);
}
} else {
return object;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return joinPoint.proceed(joinPoint.getArgs());
}
private Object cacheHit(MethodSignature signature, String key) {
String strJson = (