登录
首页 >  Golang >  Go问答

Goroutines 通信通道仅被消费一次

来源:stackoverflow

时间:2024-03-18 16:09:24 437浏览 收藏

在 Go 中使用协程和通道进行通信时,遇到一个问题。使用通道进行通信,但只能消费一次通道中的内容。这个问题导致 HTTP GET 请求无法正常处理,系统挂起直到超时。通过分析代码,发现问题出在通道的读取方式上,通道仅被读取一次,导致通道被阻塞,无法写入新的数据。

问题内容

我第一次尝试使用 go-routine 和通道通信在 golang (1.12) 中编写代码。我有 telegram 机器人和一段代码,可以在发生某些更新并需要答案时与机器人进行通信。同时,我尝试放置一些 web 服务,该服务将通过 http get 获取消息并将其发送给 bot。事实上它确实有效,但只有一次。之后bot部分仍然工作,但是无法执行http get请求,它一直挂到超时。

我尝试使用带缓冲区的通道,但在这种情况下它完全停止工作。

//App is a structure with Bot objects
type App struct {
    Router *mux.Router
    Bot
}

//Initialize is method to initialize App session
func (a *App) Initialize() {

    var err error

    a.Bot.BotAPI, err = telegram.NewBotAPI(TelegramBotAPIkey)
    checkErr(err)

    a.Router = mux.NewRouter()
    a.initializeRoutes()
    msgChanel = make(chan string)
}


func (a *App) initializeRoutes() {
    a.Router.HandleFunc("/", a.homePage).Methods("GET")
    a.Router.Path("/message/send").Queries("msg", "{msg}").HandlerFunc(a.getMessage).Methods("GET")
}


}

// Handling of requests to send/message
func (a *App) getMessage(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "-----Send message to Bot-------")
    vars := mux.Vars(r)
    if vars["msg"] != "" {
        fmt.Fprintln(w, vars["msg"])
        msgChanel <- vars["msg"]
    }

// Run is all about running application
func (a *App) Run() {

    var wg sync.WaitGroup
    wg.Add(2)


    go func() {
        defer wg.Done()
        msg := <-msgChanel
        a.Bot.generateAnswer(msgid, msg)
    }()

    go func() {

        var msg string

        defer wg.Done()
        a.Bot.BotAPI.Debug = true

        u := telegram.NewUpdate(0)
        u.Timeout = 60

        updates, err := a.Bot.BotAPI.GetUpdatesChan(u)
        checkErr(err)

        for update := range updates {
            if update.Message == nil {
                continue
            }
            msg = ""
            msgid = update.Message.Chat.ID
            a.Bot.generateAnswer(msgid, msg)
        }
    }()

    log.Fatal(http.ListenAndServe(":8080", a.Router))

    wg.Wait()

}

我的问题是没有错误消息。我运行应用程序,然后它在 bot 通信方面工作,但与 web 服务的通信仅发生一次。我的第一个想法是,这是因为通道阻塞,但是我将字符串发送到通道,然后我读取它,所以它不应该有任何阻塞。所以我的期望是,每次当我发送带有消息文本的 http get 时,它将立即发送到机器人,并且系统已准备好接收下一个请求。


解决方案


似乎“msgChanel”仅通过“msg := <-msgChanel”读取一次。通道被阻塞并且无法由 HTTP 请求处理程序写入。也许您应该使用 for 循环读取通道值。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>