如何在并发goroutine中超时截止后继续“继续”?

如何解决如何在并发goroutine中超时截止后继续“继续”?

我正在对不同URL进行并发GET请求(在这种情况下为1000)。对于这些要求,我遵循了消费者-生产者的设计。有50个工人(goroutines-爬虫)和1个生产者(使用url填充频道)。

问题:我已将客户端中的超时设置为15秒(我不想为每个请求等待15秒以上)。但是,当URL使goroutine等待15秒以上时,我的代码会以

退出

超出上下文期限(读取正文时Client.Timeout或上下文取消)

期望的行为:当服务器耗时超过15秒时,我希望相关的goroutine仅在下一个URL上继续

这是代码段:

package main

import (
    "bufio"
    "fmt"
    "io"
    "log"
    "net/http"
    "os"
    "sync"
    "time"
)

func crawler(wg *sync.WaitGroup,urlChannel <-chan string) {

    defer wg.Done()
    client := &http.Client{Timeout: 15 * time.Second} // single client is sufficient for multiple requests

    for urlItem := range urlChannel {

        req1,_ := http.NewRequest("GET","http://"+urlItem,nil)                                           // generating the request
        req1.Header.Add("User-agent","Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/74.0") // changing user-agent
        resp1,respErr1 := client.Do(req1)                                                                  // sending the prepared request and getting the response
        if respErr1 != nil {
            fmt.Println("server error",urlItem)
            continue
        }

        if resp1.StatusCode/100 == 2 { // means server responded with 2xx code

            f1,fileErr1 := os.Create("200/" + urlItem + "_original.txt") // creating the relative file
            if fileErr1 != nil {
                fmt.Println("file error",urlItem)
                log.Fatal(fileErr1)
            }

            _,writeErr1 := io.Copy(f1,resp1.Body) // writing the sourcecode into our file
            if writeErr1 != nil {
                fmt.Println("file error",urlItem)
                log.Fatal(writeErr1)
            }
            f1.Close()
            resp1.Body.Close()

            fmt.Println("success:",urlItem)

        }
    }
}

func main() {

    var wg sync.WaitGroup // synchronization to wait for all the goroutines

    file,err := os.Open("urls.txt") // the file containing the url's
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close() // don't forget to close the file

    urlChannel := make(chan string) // create a channel to store all the url's

    _ = os.Mkdir("200",0755) // if it's there,it will create an error,and we will simply ignore it

    for i := 0; i < 50; i++ {
        wg.Add(1)
        go crawler(&wg,urlChannel)
    }

    scanner := bufio.NewScanner(file) // each line has another url
    for scanner.Scan() {
        urlChannel <- scanner.Text()
    }
    close(urlChannel)
    wg.Wait()
}

具体地说,我以为我在这里处理问题(但显然我没有):

resp1,respErr1 := client.Do(req1)                                                              
// sending the prepared request and getting the response
if respErr1 != nil {
    fmt.Println("server error",urlItem)
    continue
}

如何实现所需的行为(如果达到超时则跳过URL)?

解决方法

可能在这里:

           _,writeErr1 := io.Copy(f1,resp1.Body) // writing the sourcecode into our file
            if writeErr1 != nil {
                fmt.Println("file error",urlItem)
                log.Fatal(writeErr1)
            }

此操作的结果不一定是写入错误,它可能是读取错误,在这种情况下,可能是。读取响应正文会超时。

在这种情况下,请勿致电log.Fatal

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-