2015-05-29 65 views
0

我有以下的代碼來構建與Java API谷歌日曆服務(使用服務帳號):緩存谷歌日曆憑證或服務

/** 
* 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憑證=新的GoogleCredential.Builder()...)佔用了大部分時間,四分之一秒,我會嘗試緩存,開始,看看它如何,但任何答案讚賞。

+0

只要訪問令牌有效,服務就可以重用,它是短暫的令牌,因此請求刷新令牌(通過選擇offline_type ='refresh')檢查此鏈接https://developers.google.com/identity/protocols/OAuth2WebServer。每個應用程序都有一個配額(默認)爲每個API。這決定了可以向每個API發出多少請求。請查看此鏈接https://developers.google.com/google-apps/calendar/pricing – SGC

回答

0

由於您沒有直接指定訪問令牌,所以GoogleCredential會自動刷新令牌。您已經看起來跟在the OAuth 2 documentation之後,所以沒什麼必要。