springboot 实现限制频繁访问、限流


使用AOP来实现
package com.elastic.test.config;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @author ljr
 * @date 2022-11-24 10:07
 */
@Documented
@Retention(RUNTIME)
@Target(ElementType.METHOD)
public @interface HttpConfig {
    /**
     * 标识唯一
     * @return
     */
    String value();

    /**
     * 允许请求次数
     * @return
     */
    long jc();

    /**
     * 检测时间范围秒
     * @return
     */
    int time();
}
package com.elastic.test.config;

import com.elastic.test.conrtoller.HttpMap;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * @author ljr
 * @date 2022-11-24 10:07
 */
@Aspect
@Component
public class HttpAnnoImpl {

    private HttpMap httpMap;

    @Bean
    public void initHttpMap(){
        this.httpMap = new HttpMap();
    }

    @Before(value = "@annotation(httpConfig)", argNames = "httpConfig")
    public void before(HttpConfig httpConfig) {
        Long[] value   = httpMap.get(httpConfig.value());
        long   nowTime = System.currentTimeMillis();
        if (ObjectUtils.isEmpty(value)) {
            long time = nowTime + httpConfig.time() * 1000L;
            value = new Long[]{time, 0L};
            httpMap.put(httpConfig.value(), value);
            return;
        }

        if(value[0] < nowTime) {
            httpMap.remove(httpConfig.value());
            return;
        }

        if (value[1] > httpConfig.jc()) {
            httpMap.remove(httpConfig.value());
            throw new RuntimeException();
        }

        value[1] = value[1] + 1;
        httpMap.put(httpConfig.value(), value);
    }
}
定义一个map存放请求记录
package com.elastic.test.conrtoller;

import java.util.HashMap;

/**
 * @author ljr
 * @date 2022-11-24 10:07
 */
public class HttpMap extends HashMap<String, Long[]> {}
class:TestController
@HttpConfig(value = "test", jc = 5, time = 2)
@GetMapping("/test")
public String test() throws IOException {
    return  "成功访问";
}


0 0
讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
帮助