Share variables between hosts with Go

huangapple go评论70阅读模式
英文:

Share variables between hosts with Go

问题

我有一个用golang编写的应用程序,它会将基本数据加载到全局变量中,以便使应用程序响应更快,并导出一个HTTP接口,以便在用户对数据库进行更改时更新变量。

但是我部署了另一台服务器,并使用了代理。出现了一个问题,当用户发送HTTP请求到更新URL时,它会将流量加载到其中一台服务器上。因此,只有该服务器会更新这个变量,其他服务器不会更新。

例如utils.go:

package utils

var BasicDatas map[string]*MyModel

func UpdateVar(){
// 做一些工作
}
func PreLoadVar(){
// 预加载数据到basicDatas
}

和main.go:

package main
import(
"codebase/utils"
)
func main(){
utils.PreLoadVar()
}

所以是否有办法在多个主机之间共享变量?或者是否有任何库可以帮助完成这项工作?

Nsq.io似乎是一个不错的选择,但如果有更简单的选择,我想寻找一个更简单的选择。谢谢 Share variables between hosts with Go

英文:

I have an application write in golang,and it will load the basic data to global var,so make the application response fast,and export a http interface to update the var when user make changes to the database.

But i deploy another server,and used proxy.There comes a problem,when user send http request to the update url,it will load traffic to one of the servers.So that server update this var,but others not.

such as utils.go:

package utils

var BasicDatas map[string]*MyModel

func UpdateVar(){
// do some work
}
func PreLoadVar(){
// preload data to basicDatas
}

and the main.go

package main
import(
"codebase/utils"
)
func main(){
utils.PreLoadVar()
}

so if there anyway to share the var between multi hosts?Or any libiary can help do this work?

Nsq.io seem a good choice,but i want to seek a more simple one if there is.
thanks:)

答案1

得分: 1

你的全局变量是一种非常简单的缓存形式,当你在多个服务器上运行应用程序时,这种缓存方式很容易出现问题。有几种方法可以解决这个问题:

  1. 如Bill Nelson建议的那样:将数据库作为中央存储,不在应用程序中缓存数据。
  2. 使用简单的键值存储来外部化缓存,例如使用Redis和Go中的许多Redis客户端之一。
  3. 使用分布式缓存,例如groupcache。

如果你有太多的时间,你可以使用像nsq这样的消息传递解决方案来实现自己的分布式缓存,但我建议不要这样做-这不是一个简单的问题。

英文:

Your global variable is a very simple form of caching, which is well known to be problematic when you are running your application on multiple servers. There are several ways to fix this problem:

  1. As suggested by Bill Nelson: use your database as the central storage and do not cache your data in your application at all.
  2. Externalize your cache with a simple key-value store, for example using Redis together with one of the many Redis clients in Go.
  3. Use a distributed cache such as groupcache.

If you have too much time on your hands you could use a messaging solution like nsq to implement your own distributed cache, but I would advise against it - this is not an easy problem.

huangapple
  • 本文由 发表于 2014年10月9日 01:39:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/26263057.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定