首页 > 解决方案 > Google Drive API 非常慢

问题描述

我使用从 Google 自己的.NET 快速入门中复制的以下代码来列出您的 Google Drive 帐户中的文件(auth 部分已调整为使用按照此处概述的步骤获得的刷新令牌)。

using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using System;
using System.Diagnostics;

namespace GoogleTest {
    class Program {
        [STAThread]
        static void Main(string[] args) {
            var sw = Stopwatch.StartNew();
            var secrets = new ClientSecrets() {
                ClientId = "paste-your-client-id-here",
                ClientSecret = "paste-your-client-secret-here"
            };
            var token = new TokenResponse { RefreshToken = "paste-your-refresh-token-here" };
            var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
                new GoogleAuthorizationCodeFlow.Initializer {
                    ClientSecrets = secrets
                }),
                "user",
                token);

            Console.WriteLine($"1: {sw.Elapsed}");
            // Create the service.
            var service = new DriveService(new BaseClientService.Initializer() {
                HttpClientInitializer = credentials
            });
            Console.WriteLine($"2: {sw.Elapsed}");
            // Define parameters of request.
            var listRequest = service.Files.List();
            listRequest.PageSize = 10;
            listRequest.Fields = "nextPageToken, files(id, name)";

            Console.WriteLine($"3: {sw.Elapsed}");
            // List files.
            var files = listRequest.Execute().Files;
            Console.WriteLine($"4: {sw.Elapsed}");
            if (files != null && files.Count > 0) {
                foreach (var file in files) {
                    Console.WriteLine("{0} ({1})", file.Name, file.Id);
                }
            } else {
                Console.WriteLine("No files found.");
            }
            Console.WriteLine($"5: {sw.Elapsed}");
        }
    }
}

运行上面的代码会产生以下几行的输出:

1: 00:00:00.1075210
2: 00:00:00.1881154
3: 00:00:00.1987953
4: 00:00:12.5158776
No files found.
5: 00:00:12.5166778
Press any key to continue . . .

换句话说,var files = listRequest.Execute().Files通话需要 10 秒或更长时间。通常它甚至需要长达 20 秒。

当然,对于这样一个微不足道的请求,这不可能是正常的响应时间。我在这里错过了什么吗?如您所见,相关的 Google Drive 帐户甚至不包含任何文件并且完全为空。

标签: performancegoogle-apigoogle-drive-apigoogle-oauthgoogle-api-dotnet-client

解决方案


Google API 的响应时间取决于很多变量。

  1. 在您来电的同时,其他用户在服务器上做什么
  2. 一天中什么时候打来电话会增加其他人也在运行他们的 cron 作业的机会。
  3. 你的网速。

你需要记住这是一个免费的 api,你得到你所支付的。是的,有时电话回复很慢,但您不为此付费。


推荐阅读