使用 Google Pub/Sub 轮询订阅器的频道
来源:stackoverflow
2024-03-03 18:42:25
0浏览
收藏
你在学习Golang相关的知识吗?本文《使用 Google Pub/Sub 轮询订阅器的频道》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!
问题内容
我正在尝试在 golang 中创建一个 google pubsub 订阅者,我一次接收 100 条消息,然后将它们写入 influx。我正在尝试使用渠道来执行此操作,如下所示:
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
我认为一旦通道满了,它应该阻塞直到通道被清空
这是我用作参考的 pubsub pull 代码。
解决方案
当您在频道上发送了所需数量的消息后,关闭频道并取消上下文。尝试使用 the documentation 中演示的在收到一定数量的消息后取消的技术。由于您的缓冲区为 100,并且您尝试一次消费 100 条消息,所以这就是数字。如果您希望程序退出,请关闭通道,以便 writeinflux 中的 for e := range ch 循环达到停止点,并且不会阻塞等待更多元素添加到通道中。
请注意 the Go pubsub API doc 中的这一点:
这并不是阻碍你的主 goroutine 的原因,但是如果没有取消,你的 pullmsgs goroutine 将不会自行退出。
此外,检查 unmarshal 上的错误。如果此时您不想在代码中处理解组错误,请考虑更改通道类型并发送 msg 或 msg.data,并在通道接收时进行解组。
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()
}今天关于《使用 Google Pub/Sub 轮询订阅器的频道》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
如何在Windows 11中访问局域网电脑时输入用户名和密码?
- 上一篇
- 如何在Windows 11中访问局域网电脑时输入用户名和密码?
- 下一篇
- 处理 SQL 事务已完成错误的方法
查看更多
最新文章
-
- Golang · Go问答 | 25分钟前 | go · pprof · Go alloc_space inuse_space heap profile
- Go heap profile inuse_space 与 alloc_space 的选择
- 350浏览 收藏
-
- Golang · Go问答 | 45分钟前 | go · 性能排查 ·
- Go runtime/trace 观察阻塞区域的阅读方式
- 283浏览 收藏
-
- Golang · Go问答 | 1小时前 | Go问答 · Go pprof 性能剖析 goroutine泄漏 并发排查
- Go pprof goroutine 泄漏剖析的采样方法
- 104浏览 收藏
-
- Golang · Go问答 | 1小时前 | 垃圾回收 · 资源管理 · Go问答 · Go 资源释放 AddCleanup close SetFinalizer
- Go SetFinalizer 不适合资源关闭的替代方案
- 439浏览 收藏
-
- Golang · Go问答 | 1小时前 |
- Go runtime.KeepAlive 防止句柄过早回收
- 489浏览 收藏
-
- Golang · Go问答 | 2小时前 |
- Go Signal Stop 与退出流程的竞态处理
- 168浏览 收藏
-
- Golang · Go问答 | 2天前 |
- Go ColumnTypes 推断动态查询字段的安全用法
- 319浏览 收藏
-
- Golang · Go问答 | 2天前 | Go问答 · Go 错误检查 database/sql Rows.Err
- Go Rows.Err 在迭代结束后的错误检查
- 266浏览 收藏
-
- Golang · Go问答 | 2天前 |
- Go sql.Scan NULL 到字符串失败的字段适配
- 388浏览 收藏
-
- Golang · Go问答 | 2天前 |
- Go Tx.Stmt 复用预处理语句的生命周期
- 154浏览 收藏
-
- Golang · Go问答 | 2天前 |
- Go 事务隔离级别设置未生效的驱动边界
- 165浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 289次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 342次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 344次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 308次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 130次使用
查看更多
相关文章
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go tls.GetCertificate 为什么收不到空 ServerName 请求
- 2026-09-27 501浏览
-
- Go sql.Tx提交成功前读取结果导致事务边界混乱的修复方法
- 2026-09-20 501浏览
-
- Go select 用 time.After 做超时有什么资源代价
- 2026-09-10 501浏览

