缓存 Google 日历凭据或服务

Caching Google calendar credentials or service

我有以下代码可以使用 Java API(使用服务帐户)构建 Google 日历服务:

/**
 * Return a google Calendar object for interacting with the calendar API.
 * Return null if it can't be built for any reason
 */
private Calendar buildGoogleCalendarService() throws GeneralSecurityException, IOException {
    String googleUsername = this.getGoogleUsername();
    if (googleUsername == null) {
        return null;
    }
    String path = AuthManager.class.getClassLoader().getResource("").getPath();
    File privateKey = new File(path + "/google_key.p12");
    if (!privateKey.exists()) {
        logger.error("Google private key not found at " + privateKey.getAbsolutePath());
        return null;
    }
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
            .setJsonFactory(jsonFactory).setServiceAccountId(AppProperties.googleAppEmailAddress)
            .setServiceAccountPrivateKeyFromP12File(privateKey)
            .setServiceAccountScopes(Collections.singleton(CalendarScopes.CALENDAR))
            .setServiceAccountUser(googleUsername).build();
    Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName(AppProperties.appName).build();
    return service;
}

它在一些基本测试中运行良好,问题是凭据/服务可以重复使用多长时间?即在重新生成之前你可以使用它发出多少 API 请求?此服务器应用程序可能会处理大量 API 次调用,并且在重新启动之间会持续几个月。

做一些计时,凭证构建阶段(GoogleCredential credential = new GoogleCredential.Builder()...)花费的时间最多,大约。四分之一秒,我将首先尝试缓存它并查看它的运行情况,但感谢任何答案。

由于您没有直接指定访问令牌,GoogleCredential 将自动刷新令牌。您似乎已经在关注 the OAuth 2 documentation,因此没有其他必要了。