以下是一個經過生產驗證的 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
}// 初始化