【问题标题】:Caching Google calendar credentials or service缓存 Google 日历凭据或服务
【发布时间】:2015-05-29 11:40:39
【问题描述】:

我有以下代码使用 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()...) 花费最多的时间,大约。四分之一秒,我将尝试缓存它以开始并看看它是如何进行的,但任何答案都值得赞赏。

【问题讨论】:

标签: java google-api google-calendar-api google-api-java-client


【解决方案1】:

由于您没有直接指定访问令牌,GoogleCredential 将自动刷新令牌。您似乎已经在关注the OAuth 2 documentation,因此无需再进行任何操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多