Spring Boot 3:使用自定义注解、拦截器和Redis实现高并发接口限流

在高并发系统中,接口限流是一种重要的手段,可以有效防止系统过载。我们将使用SpringBoot 3来实现这一功能,通过自定义注解和拦截器,结合Redis来存储和管理请求数据,从而实现动态的限流控制。

为什么要实现接口限流?

在高并发环境下,接口限流是一种关键手段,能够有效防止系统过载。通过限制每秒的请求次数,可以保护服务器资源,防止因瞬时大量请求导致的崩溃或性能下降。此外,接口限流还能提升用户体验,确保每个用户都能获得稳定的服务响应。通过结合自定义注解、拦截器和Redis,我们可以实现灵活且高效的限流机制,适应不同场景的需求。

设置SpringBoot项目

首先,我们需要创建一个SpringBoot项目,并添加必要的依赖。打开pom.xml文件,添加以下依赖:


<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Spring Boot Starter Data Redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!-- Jedis -->
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
    </dependency>
</dependencies>

创建自定义注解

我们需要一个自定义注解来标记需要限流的接口。创建一个新的注解类RateLimit.java:


package com.example.ratelimit;

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

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimit {
    int value(); // 每秒允许的请求数
}

实现拦截器

接下来,创建一个拦截器RateLimitInterceptor.java,在请求到达控制器之前进行限流检查:


package com.example.ratelimit;

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;

@Component
public class RateLimitInterceptor implements HandlerInterceptor {

    private final RedisService redisService;

    public RateLimitInterceptor(RedisService redisService) {
        this.redisService = redisService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            RateLimit rateLimit = handlerMethod.getMethodAnnotation(RateLimit.class);

            if (rateLimit != null) {
                String key = handlerMethod.getBeanType().getName() + ":" + handlerMethod.getMethod().getName();
                int maxRequests = rateLimit.value();

                if (!redisService.isAllowed(key, maxRequests)) {
                    response.setStatus(HttpServletResponse.SC_TOO_MANY_REQUESTS);
                    response.getWriter().write("Too many requests");
                    return false;
                }
            }
        }
        return true;
    }
}

集成Redis实现限流

创建一个RedisService类,用于与Redis交互,存储和检查请求数据:


package com.example.ratelimit;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class RedisService {

    private final StringRedisTemplate redisTemplate;

    public RedisService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public boolean isAllowed(String key, int maxRequests) {
        String count = redisTemplate.opsForValue().get(key);

        if (count == null) {
            redisTemplate.opsForValue().set(key, "1", Duration.ofSeconds(1));
            return true;
        } else if (Integer.parseInt(count) < maxRequests) {
            redisTemplate.opsForValue().increment(key);
            return true;
        } else {
            return false;
        }
    }
}

完整代码示例

最后,将拦截器添加到SpringBoot配置中,并标记需要限流的接口:

package com.example;

import com.example.ratelimit.RateLimitInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    private final RateLimitInterceptor rateLimitInterceptor;

    @Autowired
    public WebConfig(RateLimitInterceptor rateLimitInterceptor) {
        this.rateLimitInterceptor = rateLimitInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(rateLimitInterceptor);
    }
}

示例控制器:


package com.example;

import com.example.ratelimit.RateLimit;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @RateLimit(5) // 每秒允许5次请求
    @GetMapping("/test")
    public String test() {
        return "Hello, world!";
    }
}

总结

通过本文的介绍,我们学习了如何在SpringBoot 3中使用自定义注解、拦截器和Redis来实现高并发接口限流。这种方法可以帮助我们有效控制API请求速率,保护系统免受过载影响。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值