使用Google Cloud Storage JSON API设置超时

时间:2016-10-21 18:57:00

标签: google-cloud-storage

我正在向gcs写一些字节,并希望使用Google提供的JSON API包装器,但是超时。目前我有这个:

storage = new Storage
            .Builder(GoogleNetHttpTransport...)
StorageObject storageObject = new StorageObject().setBucket(bucket).setName(path);
Storage.Objects.Insert insertObject =
                storage.objects().insert(bucket, storageObject, content).setName(path);
insertObject.execute();
    }

是否有一种简单的方法可以向CloudStorageStorageObject.execute添加超时?

1 个答案:

答案 0 :(得分:1)

事实证明,存储抽象import com.google.api.services.storage.Storage可以set timeouts on initialization与您的凭据分开HttpRequestInitializers

如果您为每个GCS操作创建了MyGCSAbstraction,则可以执行以下操作:

private static HttpRequestInitializer setHttpTimeout(final HttpRequestInitializer requestInitializer) {
    return new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest httpRequest) throws IOException {
            requestInitializer.initialize(httpRequest);
            httpRequest.setConnectTimeout(1000); // ms
            httpRequest.setReadTimeout(1000); // ms
        }
    };
}

MyGCSAbstraction(String applicationName, Credential credential) throws GeneralSecurityException, IOException {
    Builder builder = new Storage.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), setHttpTimeout(credential));
    builder.setApplicationName(applicationName);
    storage = builder.build();
}