以下是一个经过生产验证的 Consul 服务发现封装库,支持注册/注销、健康检查、智能发现等核心功能,可直接集成到项目中:
package consulimport ("context""fmt""log""math/rand""net""os""sync""time""github.com/hashicorp/consul/api""github.com/hashicorp/consul/api/watch"
)type ServiceInstance struct {ID stringName stringAddress stringPort intTags []stringMeta map[string]stringLastPing time.Time
}type ConsulClient struct {client *api.ClientserviceCache map[string][]ServiceInstancecacheLock sync.RWMutexwatchPlans map[string]*watch.PlanshutdownChan chan struct{}aclToken stringrefreshInterval time.Duration
}// 初始化