简体   繁体   English

使用API​​Spark restlet扩展限制对Restlet资源的请求

[英]Limit request on a Restlet resource with APISpark restlet extension

Here's my code to limit the number of request for minute: 这是我的代码,用于限制分钟的请求数:

        MethodAuthorizer ma = createMethodAuthorizer();
        ma.setNext(router);

        FirewallRule rule = new PeriodicFirewallCounterRule(60, TimeUnit.SECONDS, new IpAddressCountingPolicy());
        ((PeriodicFirewallCounterRule)rule).addHandler(new RateLimitationHandler(new UniqueLimitPolicy(10)));
        FirewallFilter firewallFiler = new FirewallFilter(getContext(), list(rule));
        firewallFiler.setNext(ma);

        return ma;

The problem is that there is no error, but even if more than 10 request is requested from the resource still it does not throw "Too Many Request" 问题是没有错误,但是即使从资源请求了10个以上的请求,它也不会抛出“ Too Many Request”

I make it work using your configuration code within a GAE project and with the dev server. 我使用GAE项目中的配置代码以及开发服务器使它正常工作。

I used the version 2.3.1 of Restlet / version 1.9.18 of GAE and the following code as a client: 我使用Restlet的2.3.1版本/ GAE的1.9.18版本以及以下代码作为客户端:

public static void main(String[] args) {
    int i = 0;
    try {
        while (i < 30) {
            ClientResource cr = new ClientResource("http://localhost:8080/test");
            Representation repr = cr.get();
            System.out.println(">> call #"+i);
            Thread.sleep(100);

            i++;
        }
    } catch (Exception ex) {
        System.out.println(">> call #" + i + " failed");
        ex.printStackTrace();
    }
}

I have the following exception after on the 10th call: 在第10次通话后,我遇到以下异常:

>> call #0
>> call #1
>> call #2
>> call #3
>> call #4
>> call #5
>> call #6
>> call #7
>> call #8
>> call #9
>> call #10 failed
429 (429) - The server is refusing to service the request because the user has sent too many requests in a given amount of time ("rate limiting")
    at org.restlet.resource.ClientResource.doError(ClientResource.java:590)
    at org.restlet.resource.ClientResource.handleInbound(ClientResource.java:1153)
    at org.restlet.resource.ClientResource.handle(ClientResource.java:1048)
    at org.restlet.resource.ClientResource.handle(ClientResource.java:1023)
    at org.restlet.resource.ClientResource.handle(ClientResource.java:928)
    at org.restlet.resource.ClientResource.get(ClientResource.java:636)
    at org.restlet.gae.test.GaeRestletClient.main(GaeRestletClient.java:15)

Hope it helps you, Thierry 希望对您有帮助,蒂埃里

you can also rely on the ApisparkService (I've tested it using the release v2.3.2) of the framework: 您还可以依赖框架的ApisparkService(我已经使用v2.3.2版对其进行了测试):

public TestApplication() {
    super();
    ApiSparkService as = new ApiSparkService();
    as.setFirewallEnabled(true);
    as.getFirewallConfig().addIpAddressesPeriodicCounter(60, TimeUnit.SECONDS, 10);
    getServices().add(as);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM