go - Golang:RabbitMQ 接收器 + 并发地图 + http 服务器
问题描述
TL;博士
我该怎么做才能使两个服务(rabbitMQ 消费者 + HTTP 服务器)共享同一个地图?
更多信息
我是 Golang 的新手。这是我想要实现的目标:
我有一个 RabbitMQ 消费者接收一些 json 格式的消息并将它们存储到 并发 map中。另一方面,我需要一个 HTTP 服务器,它可以在 GET 请求到达时从并发映射中发送数据。
我有点知道我需要"net/http"
HTTP 服务器包和 rabbitMQ 客户端包。
但是,我不确定这两个服务如何共享同一张地图。有人可以提供一些想法吗?先感谢您!
编辑
我能想到的一种可能的解决方案是用 Redis 替换并发映射。因此,当消息到达时,正在运行的消费者将数据发送到 Redis 服务器,然后 http 服务器将从 Redis 中的数据提供 GET 请求。但是有没有更好的方法来实现我的目标而不添加这个额外的层(Redis)?
解决方案
假设您的两个“服务”存在于同一个 Go 程序中,依赖注入。您可以定义一种类型来包装您的地图(或提供等效功能),在应用程序启动时对其进行实例化,并将其注入 HTTP 处理程序和 MQ 使用者。
以下代码旨在说明该概念:
package mymap
// imports
type MyMap struct {
// fields
}
package main
// imports
func main() {
...
// instantiate the shared map object
sharedMap := &MyMap{ /* init fields as appropriate */ }
mqconsumer := &mqpkg.Consumer{
SharedMap: sharedMap // inject the map obj into the mq consumer
// ...
}
// start the mq consumer
// inject the map obj into the http handler
http.HandleFunc("/foo", handlerWithMap(sharedMap))
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handlerWithMap(mymap *mymap.MyMap) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// here the http handler is able to access the shared map object
}
}
话虽如此,除非您的应用程序有特殊要求,否则我建议您实现自己的同步地图。sync
用这个包来完成这件事并不难。使用第三方库的缺点是您失去了类型安全性,因为它们的签名必须设计为接受和返回interface{}
's。
推荐阅读
- bean-validation - protobuf 生成的 Java 对象上的级联 bean 验证不起作用
- python - 如何停止异步循环
- paperclip - Ruby 3 迁移:回形针文件的新asset_content_type
- c# - 获取泛型接口中提供的泛型类型的名称
- python - Pycharm执行后,运行光标到控制台
- material-ui - 材质 ui 选项卡不适用于 nextjs 链接
- amazon-web-services - 获取 S3 存储桶中所有对象的标签
- search - “您的意思是”建议不适用于 sharepoint 在线网站
- javascript - 正则表达式模式用 javascript 中的超链接地址替换本地地址
- javascript - 如何在 React 应用上运行亚马逊原生购物广告?