在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中實現限流的幾種方式,你可以根據具體需求選擇適合的方式來實現限流功能。