【发布时间】:2020-11-07 18:36:28
【问题描述】:
我正在尝试减少我的 discord 机器人发出的 http 请求数量。
它正在从 API 中读取数据。
使用获取的数据更新内部数据库并输出更改。
问题是:机器人所在的每个服务器的数据库都不同,这就是我使用 go 例程的地方。但是,有些服务器需要获取相同的数据,这里是我想减少 http 请求的地方。现在我正在发出请求,无论我是否已经获取了一个字符。我想创建一些可以在 go 例程之间共享的数据,然后在这些数据中进行请求搜索。
有人建议我使用互斥锁。我想。原题:Working with unbuffered channels in golang
我制作了我尝试过的真实代码的骨架:https://play.golang.org/p/mt229ns1R8m
在此示例中,master := make([][]map[string]interface{}, 0) 正在模拟不和谐服务器。
Chars 和 Chars2 将是每个单独服务器的跟踪字符。
char "Test" 对它们都是相互的,所以它应该只从 API 中获取一次。
它正在输出这个:
[[map[Level:15 Name:Test] map[Level:150 Name:Test2]] [map[Level:1500 Name:Test3] map[Level:15 Name:Test]]]
------
A call would be made
A call would be made
A call would be made
A call would be made
Cache: [map[Level:150 Name:Test2] map[Level:15 Name:Test]]Cache: [map[Level:15 Name:Test] map[Level:1500 Name:Test3]]Done
我期待的输出是:
[[map[Level:15 Name:Test] map[Level:150 Name:Test2]] [map[Level:1500 Name:Test3] map[Level:15 Name:Test]]]
------
A call would be made
A call would be made
A call would be made
Cache: [map[Level:150 Name:Test2] map[Level:15 Name:Test] map[Level:1500 Name:Test3]]Done
但是每个 goroutine 都会生成一个新的缓存。我怎样才能解决这个问题? 谢谢。
【问题讨论】:
-
看起来
Name必须是您的缓存键。为什么要保留一组地图? -
@BurakSerdar
map[string]interface{}是一个字符。不和谐服务器可以跟踪多个字符,因此[]map[string]interface{}。由于该机器人存在于许多服务器中,因此它最终成为[][]map[string]interface{}。 Name 是唯一不会改变的 char 信息的值,这就是为什么我使用它来比较本地数据和获取的数据的原因。如果有什么变化(级别、职业、成就等),我会比较所有其他字段。 -
如果你只通过字符名缓存而不关心哪个服务器,使用
map[string]map[string]interface{},这样你可以通过检查m[name]来检查你是否缓存了字符。 -
@BurakSerdar 我试过这个:play.golang.org/p/ChFMz13QJkW 仍然得到 2 个缓存而不是一个
-
您正在为每个服务器创建一个新的缓存。将缓存创建移到 goroutine 创建之外。
标签: go concurrency synchronization mutex