package com.ruoyi.framework.aspectj;

import com.ruoyi.common.exception.ServiceErrorException;

import com.ruoyi.framework.annotation.RateLimit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lidl
 * @desc 接口访问频率限制
 */
@Aspect
@Component
public class RateLimitAspect {
    private Map<String, Long> lastAccessTimeMap = new HashMap<>();

    @Around("@annotation(rateLimit)")
    public Object enforceRateLimit(ProceedingJoinPoint joinPoint, RateLimit rateLimit) throws Throwable {
        String methodName = joinPoint.getSignature().toShortString();

        // 获取当前时间
        long currentTime = System.currentTimeMillis();

        // 获取上一次访问时间
        Long lastAccessTime = lastAccessTimeMap.get(methodName);

        if (lastAccessTime == null || currentTime - lastAccessTime >= rateLimit.value()) {
            // 允许访问
            lastAccessTimeMap.put(methodName, currentTime);
            return joinPoint.proceed();
        } else {
            // 拒绝访问
            throw new ServiceErrorException("访问频率过高，请稍后再试。");
        }
    }
}
