如何在Spring Boot中为每个用户设置速率限制? [英] How to set rate limit for each user in Spring Boot?

查看:361
本文介绍了如何在Spring Boot中为每个用户设置速率限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Spring Boot Rest API,该API可以处理许多传入的请求调用.我的控制器如下所示:

I am developing a Spring Boot Rest API which handles a lots of incoming request calls. My Controller is something like below:

@RestController

public class ApiController {
    List<ApiObject>  apiDataList;   

    @RequestMapping(value="/data",produces={MediaType.APPLICATION_JSON_VALUE},method=RequestMethod.GET)
    public ResponseEntity<List<ApiObject>> getData(){                                       
        List<ApiObject> apiDataList=getApiData();
        return new ResponseEntity<List<ApiObject>>(apiDataList,HttpStatus.OK);
    }
    @ResponseBody 
    @Async  
    public List<ApiObject>  getApiData(){
        List<ApiObject>  apiDataList3=new List<ApiObject> ();
        //do the processing
        return apiDataList3;
    }
}

所以现在我想为每个用户设置一个速率限制.假设每个用户每分钟只能请求5个请求或类似的请求.如何为每个用户设置速率限制,使其每分钟只能进行5次api调用,并且如果用户请求的速率超出该限制,我可以发送回429响应?我们需要他们的IP地址吗?

So now I wanted to set a ratelimit for each user. Say every user can only request 5 request per minute or something like that. How to set the rate limit for each user to make only 5 api calls per minute and if a user requests more than that I can send a 429 response back? Do we need thier IP Address?

感谢您的帮助.

推荐答案

您在Spring中没有该组件.

You don't have that component in Spring.

  • 您可以将其构建为解决方案的一部分.创建一个过滤器并在您的spring上下文中注册它.过滤器应检查传入呼叫,并在一个时间窗口内对每个用户的传入请求进行计数.我会使用令牌桶算法,因为它是最灵活的.
  • 您可以构建一些独立于当前解决方案的组件.创建一个完成任务的API网关.您可以扩展Zuul网关,然后再次使用令牌桶算法.
  • 您可以使用已经内置的组件,例如Mulesoft ESB,它可以充当API网关并支持速率限制和限制.我自己没用过.
  • 最后,您可以使用具有速率限制和限制等功能的API管理器.结帐MuleSoft,WSO2、3Scale,Kong等...(大多数需要付费,有些是开源的,并且具有社区版).
  • You can build it as part of your solution. Create a filter and register it in your spring context. The filter should check incoming call and count the incoming requests per user during a time window. I would use the token bucket algorithm as it is the most flexible.
  • You can build some component that is independent of your current solution. Create an API Gateway that does the job. You could extend Zuul gateway and, again, use the token bucket algorithm.
  • You can use an already built-in component, like Mulesoft ESB that can act as API gateway and supports rate limiting and throttling. Never used it myself.
  • And finally, you can use an API Manager that has rate limiting and throttling and much more. Checkout MuleSoft, WSO2, 3Scale,Kong, etc... (most will have a cost, some are open source and have a community edition).

这篇关于如何在Spring Boot中为每个用户设置速率限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆