本文介绍了请求所有文件时如何避免读取超时?(谷歌驱动API)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个驱动器应用程序,它请求所有未丢弃的文件.但有时它会引发读取超时的 IOexception.有没有办法避免这种情况?

I have a drive application that requests all files that aren't trashed. But sometimes it throws a IOexception with read timeout. Is there a way to avoid this?

这是我得到的错误:

发生错误:java.net.SocketTimeoutException:读取超时

An error occurred: java.net.SocketTimeoutException: Read timed out

也许我的指数退避实现错误.

Maybe my exponential backoff is implemented wrong.

这是我用来获取文件的代码:

Here's the code I use to get the files:

private static List<File> retrieveAllNoTrashFiles(Drive service) throws IOException, InterruptedException {
    List<File> result = new ArrayList<File>();
    Files.List request = service.files().list().setQ("trashed = false").setMaxResults(1000);
    do {
        try {
            FileList files =executeRequest(service,request);
            result.addAll(files.getItems());
            request.setPageToken(files.getNextPageToken());
        } catch (IOException e) {       //here I sometimes get the read timeout
            System.out.println("An error occurred: " + e);
            request.setPageToken(null);
        }
    } while (request.getPageToken() != null
            && request.getPageToken().length() > 0);

    return result;
}

private static FileList executeRequest(Drive service,Files.List request) throws IOException, InterruptedException {
    Random randomGenerator = new Random();
    for (int n = 0; n < 5; ++n) {
        try {
            return(request.execute());
        } catch (GoogleJsonResponseException e) {
            if (e.getDetails().getCode() == 403
                    && (e.getDetails().getErrors().get(0).getReason().equals("rateLimitExceeded")
                    || e.getDetails().getErrors().get(0).getReason().equals("userRateLimitExceeded"))) {
                // Apply exponential backoff.
                Thread.sleep((1 << n) * 1000 + randomGenerator.nextInt(1001));
            }
             //else {
                // Other error, re-throw.
               // throw e;
           // }
        }
    }catch(SocketTimeoutException e){
            Thread.sleep((1 << n) * 1000 + randomGenerator.nextInt(1001));
        }
    System.err.println("There has been an error, the request never succeeded.");
    return null;
}

推荐答案

您的指数退避仅在您捕获 GoogleJsonException 时触发,而您在超时时不会收到该异常.您也可以在指数退避中捕获 SocketTimeoutException

Your exponential backoff triggers only when you catch a GoogleJsonException, which you dont get when you have a timeout. You can catch SocketTimeoutException also in your exponential backoff

这篇关于请求所有文件时如何避免读取超时?(谷歌驱动API)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 16:45