一、目的 二、运用步骤
1. 安装 consul
我们可以直接运用官方提供的二进制文件来停止安装部署,其官网地址为 https://www.consul.io/downloads
下载后为可执行文件,在我们开发实验进程中,可以直接运用 consul agent -dev 命令来启动一个单节点的 consul
在启动的打印日志中可以看到 agent: Started HTTP server on 127.0.0.1:8500 (tcp), 我们可以在阅读器直接拜访 127.0.0.1:8500 即可看到如下
这里我们的 consul 就启动成功了
2. 效劳注册
在网络编程中,普通会提供项目的 IP、PORT、PROTOCOL,在效劳管理中,我们还需求知道对应的效劳名、实例名以及一些自定义的扩展信息
在这里运用 ServiceInstance 接口来规则注册效劳时必须的一些信息,同时用 DefaultServiceInstance 完成
type ServiceInstance interface {
// return The unique instance ID as registered.
GetInstanceId() string
// return The service ID as registered.
GetServiceId() string
// return The hostname of the registered service instance.
GetHost() string
// return The port of the registered service instance.
GetPort() int // return Whether the port of the registered service instance uses HTTPS.
IsSecure() bool // return The key / value pair metadata associated with the service instance.
GetMetadata() map[string]string
}type DefaultServiceInstance struct {
InstanceId string
ServiceId string
Host string
Port int Secure bool Metadata map[string]string
}func NewDefaultServiceInstance(serviceId string, host string, port int, secure bool,
metadata map[string]string, instanceId string) (*DefaultServiceInstance, error) {
// 假设没有传入 IP 则获取一下,这个办法在多网卡的状况下,并不好用 if len(host) == 0 {
localIP, err := util.GetLocalIP() if err != nil {
return nil, err
} host = localIP } if len(instanceId) == 0 {
instanceId = serviceId + "-" + strconv.FormatInt(time.Now().Unix(), 10) + "-" + strconv.Itoa(rand.Intn(9000)+1000)
} return &DefaultServiceInstance{InstanceId: instanceId, ServiceId: serviceId, Host: host, Port: port, Secure: secure, Metadata: metadata}, nil
}func (serviceInstance DefaultServiceInstance) GetInstanceId() string {
return serviceInstance.InstanceId
}func (serviceInstance DefaultServiceInstance) GetServiceId() string {
return serviceInstance.ServiceId
}func (serviceInstance DefaultServiceInstance) GetHost() string {
return serviceInstance.Host
(责任编辑:admin)