首页 > 解决方案 > Golang:RabbitMQ 接收器 + 并发地图 + http 服务器

问题描述

TL;博士

我该怎么做才能使两个服务(rabbitMQ 消费者 + HTTP 服务器)共享同一个地图

更多信息

我是 Golang 的新手。这是我想要实现的目标:

我有一个 RabbitMQ 消费者接收一些 json 格式的消息并将它们存储到 并发 map中。另一方面,我需要一个 HTTP 服务器,它可以在 GET 请求到达时从并发映射中发送数据。

我有点知道我需要"net/http"HTTP 服务器包和 rabbitMQ 客户端包。

但是,我不确定这两个服务如何共享同一张地图。有人可以提供一些想法吗?先感谢您!

编辑

我能想到的一种可能的解决方案是用 Redis 替换并发映射。因此,当消息到达时,正在运行的消费者将数据发送到 Redis 服务器,然后 http 服务器将从 Redis 中的数据提供 GET 请求。但是有没有更好的方法来实现我的目标而不添加这个额外的层(Redis)?

标签: gorabbitmq

解决方案


假设您的两个“服务”存在于同一个 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。


推荐阅读