Skip to content

Commit

Permalink
InstanceID支持自定义 #3
Browse files Browse the repository at this point in the history
  • Loading branch information
xuanbo committed Dec 21, 2021
1 parent 843a5f1 commit 2589e1f
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 13 deletions.
14 changes: 12 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package eureka_client

import (
"fmt"
"log"
"os"
"os/signal"
Expand Down Expand Up @@ -148,7 +149,7 @@ func (c *Client) handleSignal() {
// NewClient 创建客户端
func NewClient(config *Config) *Client {
defaultConfig(config)
config.instance = NewInstance(getLocalIP(), config)
config.instance = NewInstance(config)
return &Client{Config: config}
}

Expand All @@ -169,11 +170,20 @@ func defaultConfig(config *Config) {
config.DurationInSecs = 90
}
if config.App == "" {
config.App = "server"
config.App = "unknown"
} else {
config.App = strings.ToLower(config.App)
}
if config.IP == "" {
config.IP = GetLocalIP()
}
if config.HostName == "" {
config.HostName = config.IP
}
if config.Port == 0 {
config.Port = 80
}
if config.InstanceID == "" {
config.InstanceID = fmt.Sprintf("%s:%s:%d", config.IP, config.App, config.Port)
}
}
25 changes: 16 additions & 9 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,20 @@ type Config struct {
RegistryFetchIntervalSeconds int
// 过期间隔,默认90s
DurationInSecs int
// 实例ID,默认ip:app:port
InstanceID string
// 应用名称
App string
// 端口
Port int
// Host,为空则取 IP
HostName string
// IP,为空则取本地 IP
IP string
// 端口,默认80
Port int
// 元数据
Metadata map[string]interface{}

// 服务实例信息
// 服务实例信息,基于上面的基础配置创建
instance *Instance
}

Expand Down Expand Up @@ -99,12 +106,12 @@ type LeaseInfo struct {
}

// NewInstance 创建服务实例
func NewInstance(ip string, config *Config) *Instance {
func NewInstance(config *Config) *Instance {
instance := &Instance{
InstanceID: fmt.Sprintf("%s:%s:%d", ip, config.App, config.Port),
HostName: ip,
InstanceID: config.InstanceID,
HostName: config.HostName,
App: config.App,
IPAddr: ip,
IPAddr: config.IP,
Port: &Port{
Port: config.Port,
Enabled: "true",
Expand All @@ -126,7 +133,7 @@ func NewInstance(ip string, config *Config) *Instance {
// 元数据
Metadata: config.Metadata,
}
instance.HomePageURL = fmt.Sprintf("http://%s:%d", ip, config.Port)
instance.StatusPageURL = fmt.Sprintf("http://%s:%d/info", ip, config.Port)
instance.HomePageURL = fmt.Sprintf("http://%s:%d", config.IP, config.Port)
instance.StatusPageURL = fmt.Sprintf("http://%s:%d/info", config.IP, config.Port)
return instance
}
4 changes: 2 additions & 2 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import (
"net"
)

// getLocalIP 获取本地ip
func getLocalIP() string {
// GetLocalIP 获取本地ip
func GetLocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
Expand Down

0 comments on commit 2589e1f

Please sign in to comment.