使用 APISpark restlet 扩展限制对 Restlet 资源的请求

Limit request on a Restlet resource with APISpark restlet extension

这是我限制分钟请求数的代码:

        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;

问题是没有错误,但即使从资源请求超过 10 个请求仍然不会抛出 "Too Many Request"

我在 GAE 项目和开发服务器中使用您的配置代码使其工作。

我用的是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();
    }
}

我在第 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)

希望对你有帮助, 蒂埃里

您还可以依赖框架的 ApisparkService(我已经使用版本 v2.3.2 对其进行了测试):

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