以下是一个经过生产验证的 Consul 服务发现封装库,支持注册/注销、健康检查、智能发现等核心功能,可直接集成到项目中:
package consul
import (
"context"
"fmt"
"log"
"math/rand"
"net"
"os"
"sync"
"time"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/api/watch"
)
type ServiceInstance struct {
ID string
Name string
Address string
Port int
Tags []string
Meta map[string]string
LastPing time.Time
}
type ConsulClient struct {
client *api.Client
serviceCache map[string][]ServiceInstance
cacheLock sync.RWMutex
watchPlans map[string]*watch.Plan
shutdownChan chan struct{}
aclToken string
refreshInterval time.Duration
}
// 初始化