go - 将 channel 与 google pubsub 民意调查订阅者一起使用

标签 go google-cloud-pubsub

我正在尝试在 golang 中创建一个 google pubsub 订阅者,我一次接收 100 条消息,然后将它们写入 influx。我正在尝试使用 channel 来执行此操作:

package main

import (
    "os"
    "fmt"
    "cloud.google.com/go/pubsub"
    "log"
    "sync"
    "golang.org/x/net/context"
    "encoding/json"
    clnt "github.com/influxdata/influxdb/client/v2"
    "time"
)

type SensorData struct {
    Pressure      float64 `json:"pressure"`
    Temperature   float64 `json:"temperature"`
    Dewpoint      float64 `json:"dewpoint"`
    Timecollected int64   `json:"timecollected"`
    Latitude      float64 `json:"latitude"`
    Longitude     float64 `json:"longitude"`
    Humidity      float64 `json:"humidity"`
    SensorID      string  `json:"sensorId"`
    Zipcode       int     `json:"zipcode"`
    Warehouse     string  `json:"warehouse"`
    Area          string  `json:"area"`
}

type SensorPoints struct {
    SensorData      []SensorData
}

func main () {

    messages := make(chan SensorData, 100)

    // Create a new Influx HTTPClient
    c, err := clnt.NewHTTPClient(clnt.HTTPConfig{
        Addr:     "http://localhost:8086",
        Username: "user",
        Password: "pass",
    })
    if err != nil {
        log.Fatal(err)
    }


    // Create pubsub subscriber
    ctx := context.Background()
    proj := os.Getenv("GOOGLE_CLOUD_PROJECT")
    if proj == "" {
        fmt.Fprintf(os.Stderr, "GOOGLE_CLOUD_PROJECT environment variable must be set.\n")
        os.Exit(1)
    }
    client, err := pubsub.NewClient(ctx, proj)
    if err != nil {
        log.Fatalf("Could not create pubsub Client: %v", err)
    }
    const sub = "influxwriter"


    //create influx a blank batchpoint set
    bp, err := clnt.NewBatchPoints(clnt.BatchPointsConfig{
        Database:  "sensordata",
        Precision: "s",
    })
    if err != nil {
        log.Fatal(err)
    }



    // Pull messages via the subscription.
    go pullMsgs(client, sub, messages)
    if err != nil {
        log.Fatal(err)
    }

    writeInflux(messages, bp)

    c.Close()

}


func pullMsgs(client *pubsub.Client, name string, messages chan<- SensorData) {
    ctx := context.Background()

    // [START pubsub_subscriber_async_pull]
    // [START pubsub_quickstart_subscriber]
    // Consume 10 messages.

    var mu sync.Mutex
    var sensorinfos SensorPoints
    sensorinfo := &SensorData{}

    received := 0
    sub := client.Subscription(name)
    cctx, _ := context.WithCancel(ctx)
    err := sub.Receive(cctx, func(ctx context.Context, msg *pubsub.Message) {
        msg.Ack()

        json.Unmarshal(msg.Data, sensorinfo)

        //fmt.Println(string(msg.Data))
        //fmt.Println(sensorinfo.SensorID)

        sensorinfos.SensorData = append(sensorinfos.SensorData, *sensorinfo)

        mu.Lock()
        defer mu.Unlock()
        received++
        fmt.Println("rcv: ", received)
        messages <- *sensorinfo

    })
    if err != nil {
        fmt.Println(err)
    }
    // [END pubsub_subscriber_async_pull]
    // [END pubsub_quickstart_subscriber]
}

func writeInflux(sensorpoints <- chan SensorData, bp clnt.BatchPoints) {

    for p := range sensorpoints {

        // Create a point and add to batch
        tags := map[string]string{
            "sensorId": p.SensorID,
            "warehouse": p.Warehouse,
            "area": p.Area,
            "zipcode": string(p.Zipcode),
        }

        fields := map[string]interface{}{
            "pressure":   p.Pressure,
            "humidity": p.Humidity,
            "temperature":   p.Temperature,
            "dewpoint":   p.Dewpoint,
            "longitude":   p.Longitude,
            "latitude":   p.Latitude,
        }

        pt, err := clnt.NewPoint("sensordata", tags, fields, time.Unix(p.Timecollected, 0))
        if err != nil {
            log.Fatal(err)
        }
        bp.AddPoint(pt)


    }


}

但它并没有看到每个人都通过初始的 pullMsgs 函数,只是继续打印那里的输出:

rcv:  1
rcv:  2
rcv:  3
rcv:  4
rcv:  5
rcv:  6
rcv:  7

我认为一旦 channel 满了,它应该阻塞直到 channel 被清空

这是我用作引用的 pubsub 拉取代码。

最佳答案

当您在 channel 上发送了所需数量的消息后,关闭 channel 并取消上下文。尝试使用 the documentation 中演示的技术在一些消息后取消。由于您的缓冲区是 100,并且您尝试一次使用 100 条消息,所以这就是数字。如果您希望程序退出,请关闭 channel ,以便 writeInflux 中的 for e := range ch 循环到达停止点并且不会阻塞等待更多元素将添加到 channel 。

the Go pubsub API doc 中注意这一点:

To terminate a call to Receive, cancel its context.

这不是让您的主 goroutine 停滞的原因,而是您的 pullMsgs goroutine 在没有取消的情况下不会自行退出。

此外,检查 Unmarshal 上的错误。如果您不想在代码的此时处理解码错误,请考虑更改 channel 类型并改为发送 msgmsg.Data 并在 channel 接收时解码。

cctx, cancel := context.WithCancel(ctx)
err := sub.Receive(cctx, func(ctx context.Context, msg *pubsub.Message) {
    msg.Ack()
    err := json.Unmarshal(msg.Data, sensorinfo)
    if err != nil {
         fmt.Printf("Failed to unmarshal: %s\n", err)
    }
    mu.Lock()
    defer mu.Unlock()
    received++
    fmt.Println("rcv: ", received)
    messages <- *sensorinfo
    if received == 100 {
        close(messages)  // no more messages will be sent on channel
        cancel()
    }

关于go - 将 channel 与 google pubsub 民意调查订阅者一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51717626/

相关文章:

google-cloud-platform - Google Cloud Pub/Sub 如何避免时钟偏差

go - 为什么当我通过反射构造它时,Golang yaml.v2 将我的结构转换为映射?

json - 使用列表中的不同类型解码 JSON

go - 在 Go 语言中返回其结构地址的方法

Go 中的继承

java - 谷歌发布订阅 : pull java sample client hanging

go - 如何使用个人(gcloud)凭据发布到PubSub

go - 如何在 Go 中将类型传递给函数参数

java - 云发布/订阅接收器未收到消息