Reddit APIへのアクセスを制限するレート

Reddit APIへのアクセス制限レート

1. 概要

この簡単な記事では、our small Reddit apprate limiting the way it has access to the live Reddit APIだけ改善し続けます。

簡単なアイデアは、we don’t hit their API to muchを確認したいということです。そうしないと、Redditがリクエストのブロックを開始します。 そこに到達するためにGuavaRateLimiterをうまく利用します。

2. カスタムRedditTemplate

まず、Redditテンプレート–a small client for the Reddit API –を作成しましょう。これにより、すべての低レベルの通信が1つのコンポーネントに統合されます。

@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RedditTemplate {

    @Autowired
    @Qualifier("redditRestTemplate")
    private OAuth2RestTemplate redditRestTemplate;

    private RateLimiter rateLimiter;

    public RedditTemplate() {
        rateLimiter = RateLimiter.create(1);
    }

    public JsonNode getUserInfo() {
        rateLimiter.acquire();
        return redditRestTemplate.getForObject(
          "https://oauth.reddit.com/api/v1/me", JsonNode.class);
    }

    public JsonNode submitPost(MultiValueMap params) {
        rateLimiter.acquire();
        return redditRestTemplate.postForObject(
          "https://oauth.reddit.com/api/submit", params, JsonNode.class);
    }

    public String needsCaptcha() {
        rateLimiter.acquire();
        return redditRestTemplate.getForObject(
          "https://oauth.reddit.com/api/needs_captcha.json", String.class);
    }

    public String getNewCaptcha() {
        rateLimiter.acquire();
        Map param = new HashMap();
        param.put("api_type", "json");
        return redditRestTemplate.postForObject(
          "https://oauth.reddit.com/api/new_captcha", param, String.class, param);
    }

    public OAuth2AccessToken getAccessToken() {
        rateLimiter.acquire();
        return redditRestTemplate.getAccessToken();
    }
}

ここでいくつかの興味深いことが起こっています。

まず–we’re using the Session scope for this bean –アプリ内の各ユーザー/セッションが独自のRedditTemplateインスタンスを取得するようにします。

現在、OAuth2RestTemplateは、資格情報セッションのスコープを維持するためのサポートをすでに持っていますが、ここではそれを超えて、実際のBeanインスタンスセッションのスコープを作成します。これにより、rate limit each user separatelyも可能になります。

これにより、実際のレート制限ロジックが導き出されます。簡単に言えば、GuavaRateLimiterを使用して許可before letting the request through and hitting the live API.を取得しています。

3. RedditController

次に–RedditContollerでこの新しいRedditTemplateの使用を開始しましょう–例:

@Controller
public class RedditController {
    @Autowired
    private RedditTemplate redditTemplate;

    @Autowired
    private UserRepository userReopsitory;

    @RequestMapping("/login")
    public String redditLogin() {
        JsonNode node = redditTemplate.getUserInfo();

        loadAuthentication(node.get("name").asText(),
          redditTemplate.getAccessToken());
        return "redirect:home.html";
    }
}

4. 結論

ケーススタディのこの部分では、Redditアプリケーションのレート制限をmake sure we’re not blocked by the live API for to much activityに追加しました。

これも理論上の問題ではありませんが、実際にはアプリを使用して何度か遭遇した問題です。

最終的に成熟した使いやすいアプリケーションにつながるのは、この種の小さな改善です。そのため、この特定のステップに興奮しています。