Implementing API Rate Limiting in Spring Boot with Custom Annotation and Redis

This article explains how to implement API request rate limiting in Spring Boot by creating a custom @RequestLimit annotation, using Redis to track request counts, and configuring a HandlerInterceptor and WebMvcConfig to enforce limits on controller methods.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Implementing API Rate Limiting in Spring Boot with Custom Annotation and Redis

API rate limiting ensures that a specific endpoint can be called only a limited number of times within a defined time window.

Common issue is multiple clicks causing repeated requests; traditionally solved with tokens on the web side, but now handled entirely on the backend.

Principle

The server records request counts in Redis; if the count exceeds the limit, further access is denied. Redis keys have an expiration time, after which they are removed.

Implementation

The solution uses a custom annotation @RequestLimit to specify the allowed number of requests and the time window.

import java.lang.annotation.*;

/**
 * 请求限制的自定义注解
 * 
 * @Target 注解可修饰的对象范围,ElementType.METHOD 作用于方法,ElementType.TYPE 作用于类
 * (ElementType)取值有:
 *     1.CONSTRUCTOR:用于描述构造器
 *     2.FIELD:用于描述域
 *     3.LOCAL_VARIABLE:用于描述局部变量
 *     4.METHOD:用于描述方法
 *     5.PACKAGE:用于描述包
 *     6.PARAMETER:用于描述参数
 *     7.TYPE:用于描述类、接口(包括注解类型) 或enum声明
 * @Retention定义了该Annotation被保留的时间长短:某些Annotation仅出现在源代码中,而被编译器丢弃;
 * 而另一些却被编译在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,
 * 而另一些在class被装载时将被读取(请注意并不影响class的执行,因为Annotation与class在使用上是被分离的)。
 * 使用这个meta-Annotation可以对 Annotation的“生命周期”限制。
 * (RetentionPoicy)取值有:
 *     1.SOURCE:在源文件中有效(即源文件保留)
 *     2.CLASS:在class文件中有效(即class保留)
 *     3.RUNTIME:在运行时有效(即运行时保留)
 * 
 * @Inherited
 * 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。
 * 如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
 */
@Documented
@Inherited
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestLimit {
    // 在 second 秒内,最大只能请求 maxCount 次
    int second() default 1;
    int maxCount() default 1;
}

A RequestLimitIntercept interceptor checks the annotation before method execution, retrieves the count from Redis, increments it, and returns an error response when the limit is exceeded.

package com.springcache.Filter;

import com.alibaba.fastjson.JSONObject;
import com.springcache.Entity.MyApi.RequestLimit;
import com.springcache.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @Author 我见青山多妩媚
 * @Create on 2022/4/19 17:17
 */
@Slf4j
@Component
public class RequestLimitIntercept implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * isAssignableFrom() 判定此 Class 对象所表示的类或接口与指定的 Class 参数所表示的类或接口是否相同,或是否是其超类或超接口
         * isAssignableFrom()方法是判断是否为某个类的父类
         * instanceof关键字是判断是否某个类的子类
         */
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
            //HandlerMethod 封装方法定义相关的信息,如类,方法,参数等
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            // 获取方法中是否包含注解
            RequestLimit methodAnnotation = method.getAnnotation(RequestLimit.class);
            //获取 类中是否包含注解,也就是controller 是否有注解
            RequestLimit classAnnotation = method.getDeclaringClass().getAnnotation(RequestLimit.class);
            // 如果 方法上有注解就优先选择方法上的参数,否则类上的参数
            RequestLimit requestLimit = methodAnnotation != null?methodAnnotation:classAnnotation;
            if(requestLimit != null){
                if(isLimit(request,requestLimit)){
                    responseOut(response, Result.error(403,"请求过快"));
                    return false;
                }
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
    //判断请求是否受限
    public boolean isLimit(HttpServletRequest request,RequestLimit requestLimit){
        // 受限的redis 缓存key ,因为这里用浏览器做测试,我就用sessionid 来做唯一key,如果是app ,可以使用 用户ID 之类的唯一标识。
        String limitKey = request.getServletPath()+request.getSession().getId();
        // 从缓存中获取,当前这个请求访问了几次
        Integer redisCount = (Integer) redisTemplate.opsForValue().get(limitKey);
        if(redisCount == null){
            //初始 次数
            redisTemplate.opsForValue().set(limitKey,1,requestLimit.second(), TimeUnit.SECONDS);
            System.out.println("写入redis --");
        }else{
            System.out.println("intValue-->"+redisCount.intValue());
            if(redisCount.intValue() >= requestLimit.maxCount()){
                return true;
            }
            // 次数自增
            redisTemplate.opsForValue().increment(limitKey);
        }
        return false;
    }

    /**
     * 回写给客户端
     * @param response
     * @param result
     * @throws IOException
     */
    private void responseOut(HttpServletResponse response, Result result) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null ;
        String json = JSONObject.toJSON(result).toString();
        out = response.getWriter();
        out.append(json);
    }
}

The interceptor must be registered in a WebMvcConfig class that implements WebMvcConfigurer. For Spring Boot 2.x you add the interceptor via addInterceptors(); for Spring Boot 1.x you would extend WebMvcConfigurerAdapter.

@Slf4j
@Component
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private RequestLimitIntercept requestLimitIntercept;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        log.info("添加拦截");
        registry.addInterceptor(requestLimitIntercept);
    }

    //如果集成了swagger必须要有,否则swagger无法打开,会被拦截
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
    }
}

Finally, apply the @RequestLimit annotation on controller classes or methods. Example controller demonstrates usage with different limits.

@Controller
@RequestMapping("/user")
@Api(tags = "测试:接口防刷")
@ResponseBody
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation(value = "查询用户",notes = "接口防刷测试")
    @GetMapping("/getNo")
    @RequestLimit(maxCount = 5,second = 2)
    public User queryNo(Integer userId) {
        return userService.queryNo(userId);
    }

    @GetMapping("/get")
    @RequestLimit(second = 10,maxCount = 2)
    public String query() {
        return "aaaaa";
    }
}

Running the application shows that Redis stores the request counts with a short TTL, and Swagger UI displays the endpoints correctly. Screenshots in the original article illustrate the runtime results.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendjavaredisSpring BootInterceptorannotationrate limiting
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.