package cn.quantgroup.xyqb.aspect.limit;

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.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class AccessLimitAspect {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 要求不高时 可使用。
     * setnx + expire 问题，lua解决。
     * expire问题，严谨可使用Redission。
     *
     * @param pjp
     * @throws Throwable
     */
    @Around("@annotation(cn.quantgroup.xyqb.aspect.limit.AccessLimit)")
    public Object accessLimit(ProceedingJoinPoint pjp) throws Throwable {
        Object o = null;
        AccessLimit accessLimit = ((MethodSignature) pjp.getSignature()).getMethod().getAnnotation(AccessLimit.class);
        String redisKey = accessLimit.redisKey() + "_" + pjp.getArgs()[0];
        boolean lock = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, "");
        if (lock) {
            try {
                stringRedisTemplate.expire(redisKey, 1, TimeUnit.MINUTES);
                o = pjp.proceed();
            } finally {
                stringRedisTemplate.delete(redisKey);
            }
        }
        return o;
    }

}
