【发布时间】: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()...) 花费最多的时间,大约。四分之一秒,我将尝试缓存它以开始并看看它是如何进行的,但任何答案都值得赞赏。
【问题讨论】:
-
服务可以被重复使用,只要访问令牌有效,它是短暂的令牌,所以请求刷新令牌(通过选择offline_type='refresh')检查这个链接developers.google.com/identity/protocols/OAuth2WebServer。每个应用程序的每个 API 都有一个配额(默认)。这决定了每个 API 可以发出多少请求。检查此链接developers.google.com/google-apps/calendar/pricing
标签: java google-api google-calendar-api google-api-java-client