1. 自定义注解
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface RedisLock {
String[] keyPieces();
int expireTime() default 5;
}
2.aop切面
@Slf4j
@Aspect
@Component
public class RedisLockAspect {
@Autowired
private RedisService redisService;
@Around("@annotation(redisLock)")
public Object doAround(ProceedingJoinPoint pjp, RedisLock redisLock) throws Throwable {
String key = parseKey(pjp, redisLock.keyPieces());
if (redisService.setNx(key, System.currentTimeMillis() + "", redisLock.expireTime())) {
try {
Object obj = pjp.proceed();
return obj;
} finally {
redisService.delete(key);
}
} else {
throw new BusinessException(HttpStatus.BAD_REQUEST.value(),