在Spring Boot中,可以使用以下几种方式来实现限流:
@RateLimit(max = 100, duration = 60)
@GetMapping("/api/someEndpoint")
public String someEndpoint() {
// 方法逻辑
}
@Component
public class RateLimitInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 判断访问次数是否超过限制
if (isRateLimited(request)) {
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.getWriter().write("Rate limit exceeded");
return false;
}
return true;
}
private boolean isRateLimited(HttpServletRequest request) {
// 判断访问次数是否超过限制的逻辑
}
}
在Spring Boot中注册拦截器:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private RateLimitInterceptor rateLimitInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(rateLimitInterceptor);
}
}
@Component
public class RateLimitService {
private final Cache<String, AtomicInteger> cache;
public RateLimitService() {
cache = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(1, TimeUnit.MINUTES)
.build();
}
public boolean isRateLimited(String key, int max, long duration) {
AtomicInteger counter = cache.get(key, () -> new AtomicInteger(0));
int count = counter.incrementAndGet();
if (count > max) {
return true;
}
return false;
}
}
在控制器中使用RateLimitService限流:
@RestController
public class SomeController {
@Autowired
private RateLimitService rateLimitService;
@GetMapping("/api/someEndpoint")
public String someEndpoint(HttpServletRequest request) {
String key = request.getRemoteAddr();
if (rateLimitService.isRateLimited(key, 100, 60)) {
return "Rate limit exceeded";
}
// 方法逻辑
}
}
这些是Spring Boot中实现限流的几种方式,你可以根据具体需求选择适合的方式来实现限流功能。