Golang单例模式适用于微服务的所有副本。

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

Golang Singleton for all replicas of microservice

问题

我正在使用sync.Once来在我的微服务中实现单例模式。但我不确定这是否能确保所有副本都只有一个实例。
如何在Golang中为分布式微服务创建一个单例对象?

英文:

I am using sync.once to implement singleton in my microservice. But I am not sure if this will ensure a single instance for all the replicas.
How to create a Singleton object for distributed microservices in golang?

答案1

得分: 4

它无法确保在不同环境中运行的多个进程之间的单个实例。sync 用于同步运行在主例程进程中的 go routines。

要添加在多个进程和多个微服务之间工作的锁定,您需要一个单独的第三方实例来控制它。它可以是队列消息/缓存代理(例如RabbitMQRedis)或数据库(例如PostgreSQL advisory locks)。

英文:

It cannot ensure a single instance between multiple processes running in different environments. sync is used to synchronise go routines, which are running against the main routine process.

To add locking that would work between multiple processes and multiple microservices, you need a single third-party instance, that would control it. It can be a queue message / cache broker (e.g. RabbitMQ, Redis) or database (e.g. PostgreSQL advisory locks).

huangapple
  • 本文由 发表于 2021年5月21日 18:35:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/67635225.html
匿名

发表评论

匿名网友

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

确定