限制Java中的Rest API [英] Throttling a Rest API in Java

查看:108
本文介绍了限制Java中的Rest API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加一种方法来限制来自某个客户端的每个API上的请求数量。因此,我想从根本上限制每个客户端每个API的请求数。

I wanted to add a way to throttle the number of requests coming on each API from a certain client. So, I wanted to basically limit the number of requests per API per client.

我正在使用DropWizard作为框架。有人可以推荐实现此目标的方法吗?我需要一些适用于分布式系统的东西。

I am using DropWizard as framework. Can somebody recommend the ways to achieve this? I need something that will work for Distributed system.

推荐答案

一种简单的方法是使用过滤器并将其包装在 web中的所有API调用周围。 xml 。假设您的客户端在HTTP标头中发送用于标识它们的API密钥,则可以实现这样的过滤器:

A simplistic approach would be to use a Filter and wrap it around all your API calls in web.xml. Assuming your clients send an API keys identifying them in a HTTP header, you could implement a filter like this:

public class MyThrottlingFilter extends Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpreq = (HttpServletRequest) req;
        String apiKey = httpreq.getHeader("API_KEY")

        if (invocationLimitNotReached(apiKey))
            chain.doFilter(req, res);
        else
            throw ...
    }
}

,然后像这样注册它:

<filter>
    <filter-name>MyThrottlingFilter</filter-name>
    <filter-class>com.my.throttler.MyThrottlingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyThrottlingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

当然,如果使用其他身份验证方法,则识别客户可能比这更困难,但总体思路应该相同。

Of course, identifying your clients may be more difficult than this, if you use some other authentication methods, but the general idea should be the same.

这篇关于限制Java中的Rest API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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