利用Redis+切面实现接口限流

创建一个限流注解

package com.hhc.analysis.config.annotation;

import com.hhc.analysis.common.constant.CacheConstants;

import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;

/**
 * 限流注解
 * 
 * @author ruoyi
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RateLimiter
{
    /**
     * 限流key
     */
    public String key() default CacheConstants.RATE_LIMIT_KEY;

    /**
     * 限流时间
     */
    public int time() default 1;

    /**
     * 限流次数(最大访问次数)
     */
    public int count() default 5;

    /**
     *  时间单位,默认秒
     */
    TimeUnit timeUnit() default TimeUnit.SECONDS;
}

创建一个切面类

package com.hhc.analysis.config.aspectj;

import com.hhc.analysis.common.constant.ErrorConstants;
import com.hhc.analysis.common.exception.AIDocException;
import com.hhc.analysis.config.annotation.RateLimiter;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 限流处理
 *
 * @author ruoyi
 */
@Aspect
@Component
public class RateLimiterAspect
{
    private static final Logger log = LoggerFactory.getLogger(RateLimiterAspect.class);
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 定义切点为注解
     */
    @Pointcut("@annotation(com.hhc.analysis.config.annotation.RateLimiter)")
    public void AccessLimitPointcut(){
    }

    @Before(value = "AccessLimitPointcut()")
    public void handleAccessLimit(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        RateLimiter annotation = AnnotationUtils.findAnnotation(method, RateLimiter.class);
        int accessMaxTimes = annotation.count();
        long timeOut = annotation.time();
        TimeUnit timeUnit = annotation.timeUnit();
        String key = annotation.key();
        // 如果redis不存在或已经过期
        Long expire = redisTemplate.opsForValue().getOperations().getExpire(key);
        if (!redisTemplate.hasKey(key) || Objects.requireNonNull(expire).intValue() < 0) {
            redisTemplate.opsForValue().set(key, 1, timeOut, timeUnit);
        } else {
            long increment = redisTemplate.opsForValue().increment(key).intValue();
            if (increment > accessMaxTimes) {
                throw new AIDocException(ErrorConstants.INVOKE_LIMIE, "1分钟内只能请求 " + accessMaxTimes+"次,请稍后尝试!");
            }
        }
    }
}

在调用的接口上加上@RateLimiter 就实现啦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值