登录
首页 >  Golang >  Go问答

打印后台处理程序概念/API 和通道:将作业从serveHTTP 传递到队列的问题

来源:stackoverflow

时间:2024-05-01 14:09:38 397浏览 收藏

哈喽!今天心血来潮给大家带来了《打印后台处理程序概念/API 和通道:将作业从serveHTTP 传递到队列的问题》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

这里已经得到了一些帮助,这让我在我正在尝试的这个概念上取得了进展,但它仍然不太有效,而且我遇到了一个我似乎无法解决的冲突。

我在这里尝试在流程图中说明我想要的内容 - 请注意,客户端可以是许多将发送打印作业的客户端,因此我们无法回复当时正在处理我们作业的工作人员,但对于大多数人来说会的(高峰时段不会,因为打印处理工作可能需要时间)。

type queueelement struct {
    jobid string
    rw   http.responsewriter
  donechan chan struct{}
}

type globalvars struct {
    db   *sql.db
    wg   sync.waitgroup
    jobs chan queueelement
}

func (gv *globalvars) servehttp(w http.responsewriter, r *http.request) {

    switch r.url.path {
    case "/startjob":
        fmt.printf ("incoming\r\n")

            donec := make(chan struct{}, 1) //buffered channel in order not to block the worker routine
            newprintjob := queueelement{
                    donechan: donec,    
                    jobid:    "jobid",
            }

            gv.jobs <- newprintjob
            func(donechan chan struct{},w http.responsewriter) {

                  ctx, cancel := context.withtimeout(context.background(), 5*time.second)
                    defer cancel()
                    select {
                    //if this triggers first, then this waiting goroutine would exit
                    //and nobody would be listeding the 'donechan'. this is why it has to be buffered.
                    case <-ctx.done():
                            fmt.fprintf(w, "job is taking more than 5 seconds to complete\r\n")
                            fmt.printf ("took longer than 5 secs\r\n")
                    case <-donechan:
                            fmt.fprintf(w, "instant reply from servehttp\r\n")
                            fmt.printf ("instant\r\n")
                    }
            }(donec,w)

    default:
            fmt.fprintf(w, "no such api")
    }
}

func worker(jobs <-chan queueelement) {
    for {
            job := <-jobs
            processexec ("start /i /b try.cmd")
            fmt.printf ("job done")
        //  processexec("start /i /b processandprint.exe -" + job.jobid)
            job.donechan <- struct{}{}

    }
}

func main() {
      db, err := sql.open("sqlite3", "jobs.sqlite")
      if err := db.ping(); err != nil {
        log.fatal(err)
    }   

      db.setmaxopenconns(1) // prevents locked database error
      _, err = db.exec(setupsql)
      if err != nil {
          log.fatal(err)
      }

    // create a globalvars instance
    gv := globalvars{
        db  :   db,
        jobs: make(chan queueelement),
    }
    go worker (gv.jobs)
    // create an http.server instance and specify our job manager as
    // the handler for requests.
    server := http.server{
        handler: &gv,
        addr : ":8888",
    }
    // start server and accept connections.
    log.fatal(server.listenandserve())
}

上面的代码是servehttp和工作人员在此处的帮助下,最初servehttp内部的func是一个go例程,对我来说整个冲突就在这里出现 - 这个概念是在servehttp中它产生了一个进程如果工作人员能够在 5 秒内及时处理作业,将会收到工作人员的回复。

如果工作能够在1秒内完成,我想在1秒后立即回复客户端,如果需要3秒,我想在3秒后回复,如果需要超过5秒,我将发送回复5秒后(如果工作需要13秒我仍然想在5秒后回复)。从现在开始,客户必须对工作进行轮询 - 但冲突是:

a) 当 servehttp 退出时 - 然后 responsewriter 关闭 - 并且为了能够回复客户端,我们必须将答案写入 responsewriter。

b) 如果我阻止了servehttp(就像下面的代码示例中,我不将 func 作为 go 例程调用),那么它不仅会影响单个 api 调用,而且似乎之后的所有其他调用都会受到影响,因此,第一个呼叫将及时正确地得到服务,但在第一个呼叫之后同时进入的呼叫将被阻塞操作依次延迟。

c) 如果我不阻止它 - 并将其更改为 go 例程:

gv.jobs <- newPrintJob
    go func(doneChan chan struct{},w http.ResponseWriter) {

然后没有延迟 - 可以调用许多 api - 但问题是,servehttp 立即存在,从而杀死 responsewriter,然后我无法回复客户端。

我不确定如何解决这个冲突,在不导致任何服务阻塞的情况下,我可以并行处理所有请求,但仍然能够回复有问题的 responsewriter。

有什么方法可以防止servehttp关闭响应编写器,即使该函数存在?


解决方案


我已对您的代码添加了一些更新。现在它的工作原理正如您所描述的那样。

package main

import (
    "database/sql"
    "fmt"
    "log"
    "math/rand"
    "net/http"
    "sync"
    "time"
)

type QueueElement struct {
    jobid    string
    rw       http.ResponseWriter
    doneChan chan struct{}
}

type GlobalVars struct {
    db   *sql.DB
    wg   sync.WaitGroup
    jobs chan QueueElement
}

func (gv *GlobalVars) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    switch r.URL.Path {
    case "/StartJob":
        fmt.Printf("incoming\r\n")

        doneC := make(chan struct{}, 1) //Buffered channel in order not to block the worker routine

        go func(doneChan chan struct{}, w http.ResponseWriter) {
            gv.jobs <- QueueElement{
                doneChan: doneC,
                jobid:    "jobid",
            }
        }(doneC, w)

        select {
        case <-time.Tick(time.Second * 5):
            fmt.Fprintf(w, "job is taking more than 5 seconds to complete\r\n")
            fmt.Printf("took longer than 5 secs\r\n")
        case <-doneC:
            fmt.Fprintf(w, "instant reply from serveHTTP\r\n")
            fmt.Printf("instant\r\n")
        }
    default:
        fmt.Fprintf(w, "No such Api")
    }
}

func worker(jobs <-chan QueueElement) {
    for {
        job := <-jobs
        fmt.Println("START /i /b try.cmd")
        fmt.Printf("job done")

        randTimeDuration := time.Second * time.Duration(rand.Intn(7))

        time.Sleep(randTimeDuration)

        //  processExec("START /i /b processAndPrint.exe -" + job.jobid)
        job.doneChan <- struct{}{}
    }
}

func main() {

    // create a GlobalVars instance
    gv := GlobalVars{
        //db:   db,
        jobs: make(chan QueueElement),
    }
    go worker(gv.jobs)
    // create an http.Server instance and specify our job manager as
    // the handler for requests.
    server := http.Server{
        Handler: &gv,
        Addr:    ":8888",
    }
    // start server and accept connections.
    log.Fatal(server.ListenAndServe())
}

是的,你的观点是对的“c)如果我不阻止它”

为了保存响应编写器,您不应该在其中调用 go 例程。相反,您应该将 servehttp 调用为 go-routine,大多数 http 服务器实现都是这样做的。
这样您就不会阻止任何 api 调用,每个 api 调用将在不同的 go 例程中运行,并被其功能阻止。

由于您的“jobs chan queueelement”是单个通道(不是缓冲通道),因此您的所有进程都会在“gv.jobs <- newprintjob”处被阻止.
您应该使用缓冲通道,以便所有 api 调用都可以将其添加到队列中,并根据工作完成或超时获得响应。

拥有缓冲通道也可以模拟打印机的现实内存限制。 (队列长度1为特例)

以上就是《打印后台处理程序概念/API 和通道:将作业从serveHTTP 传递到队列的问题》的详细内容,更多关于的资料请关注golang学习网公众号!

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