goeureka

package module
v0.2.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 25, 2020 License: MIT Imports: 19 Imported by: 0

README

Build Status GoDoc Status Go Report Card codecov Sourcegraph Open Source Helpers

goeureka

Goland Eureka Client for Spring Cloud Eureka 1.x

Usage
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"github.com/gorpher/goeureka"
	"io/ioutil"
	"log"
	"net/http"
	_ "net/http/pprof"
	"os"
	"os/signal"
	"strconv"
)

var client *goeureka.Client

func main() {
	app := flag.String("app", "golang-service-1", "服务名,默认值是golang-service")
	port := flag.Int("port", 8080, "端口,默认值是8080")
	flag.Parse()
	var err error
	client, err = goeureka.New(&goeureka.AppInfo{
		AppID:     *app,
		Port:      *port,
		UserName:  "fitmgr",
		Password:  "fitmgr",
		EurekaURL: "http://127.0.0.1:8761",
	}) // Performs eurekaClient registration
	if err != nil {
		panic(err)
	}
	err = client.Register()
	if err != nil {
		panic(err)
	}

	go func() {
		ch := makeShutdownCh()
		select {
		case <-ch:
			client.Deregister()
		}
	}()
	startWebServer(*port) // Starts HTTP service  (async)
}

var ignoreSignals = []os.Signal{os.Interrupt}
var forwardSignals []os.Signal

// makeShutdownCh creates an interrupt listener and returns a channel.
// A message will be sent on the channel for every interrupt received.
func makeShutdownCh() <-chan struct{} {
	resultCh := make(chan struct{})

	signalCh := make(chan os.Signal, 4)
	signal.Notify(signalCh, ignoreSignals...)
	signal.Notify(signalCh, forwardSignals...)
	go func() {
		for {
			<-signalCh
			resultCh <- struct{}{}
		}
	}()

	return resultCh
}

var healthData = `
{
"description": "Golang Eureka Discovery EurekaClient",
"status": "UP"
}
`

func startWebServer(port int) {
	http.HandleFunc("/health", func(writer http.ResponseWriter, request *http.Request) {
		writer.Header().Add("Content-Type", "application/json")
		writer.WriteHeader(http.StatusOK)
		writer.Write([]byte(healthData)) //nolint
	})
	http.HandleFunc("/call", func(w http.ResponseWriter, r *http.Request) {
		m := map[string]string{}
		request, err := http.NewRequest(http.MethodGet, "http://golang-service/info", nil)
		if err != nil {
			panic(err)
		}
		resp, err := client.Do(request)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte(err.Error()))
			return
		}
		defer resp.Body.Close() //nolint
		all, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			panic(err)
		}
		m["call"] = string(all)
		m["desc"] = "调用其他服务成功"
		v, _ := json.Marshal(m)
		w.Header().Add("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(v)
	})
	http.HandleFunc("/info", func(w http.ResponseWriter, r *http.Request) {
		ip := goeureka.GetLocalIP()
		m := map[string]string{
			"HostName":   client.AppInfo.HostName,
			"Port":       strconv.Itoa(client.AppInfo.Port),
			"InstanceID": client.AppInfo.InstanceID,
			"AppID":      client.AppInfo.AppID,
			"IP":         ip,
			"IpAddr":     client.Instance.IpAddr,
		}
		v, _ := json.Marshal(m)
		w.Header().Add("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(v)
	})
	log.Printf("Starting HTTP service at %d \n", port)
	err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
	if err != nil {
		log.Printf("An error occurred starting HTTP listener at port %d \n", port)
		log.Println("Error: " + err.Error())
	}
}
todo
  • add log level
  • add error handler
reference

Documentation

Index

Constants

View Source
const (
	ADDED    ActionType = "ADDED"
	MODIFIED            = "MODIFIED"
	DELETED             = "DELETED"
)
View Source
const (
	Netflix DataCenterInfoName = "Netflix"
	Amazon                     = "Amazon"
	MyOwn                      = "MyOwn"
)

Variables

View Source
var RETRIES = 3

Functions

func GetHostnameByIP added in v0.2.7

func GetHostnameByIP(ip string) (hostname string)

根据ip得到主机名

func GetLocalIP

func GetLocalIP() (ip string)

获取主机index最小的IP

func NewServiceCache

func NewServiceCache(timeout time.Duration) *serviceCache

开启协程,清除缓存

func NowStr added in v0.2.5

func NowStr() string

Types

type ActionType

type ActionType string

type AppInfo

type AppInfo struct {
	HostName   string // 服务机器的主机名
	IPAddress  string // 服务机器的IP地址
	AppID      string // 服务名
	InstanceID string // 服务的实例名
	Port       int    // 服务的端口
	UserName   string // 注册中心认证的用户名
	Password   string // 注册中心认证的密码
	EurekaURL  string // 注册中心认证的url地址
	LogLevel   zerolog.Level
}

type Application

type Application struct {
	Name     string     `json:"name" xml:"name"`
	Instance []Instance `json:"instance,omitempty" xml:"instance,omitempty"`
}

type Applications

type Applications struct {
	AppsHashCode string        `json:"apps__hashcode" xml:"apps__hashcode"`
	VersionDelta string        `json:"versions__delta" xml:"versions__delta"`
	Application  []Application `json:"application,omitempty" xml:"application,omitempty"`
}

type Client

type Client struct {
	AppInfo  *AppInfo
	Instance Instance
	// contains filtered or unexported fields
}

eureka客户端

func New

func New(appInfo *AppInfo) (*Client, error)

新建goeureka客户端

func (*Client) Deregister

func (c *Client) Deregister() error

下线 DELETE {{url}}/eureka/apps/{{appID}}/{{instanceID}}

func (*Client) GetAppInstanceByID

func (c *Client) GetAppInstanceByID(appID string, instanceID string) (Instance, error)

查询指定服务实例

func (*Client) GetAppInstanceSVip

func (c *Client) GetAppInstanceSVip(svips string) (Applications, error)

查询svip下的实例 GET {{url}}/eureka/svips/{{svipAddress}}

func (*Client) GetAppInstanceVip

func (c *Client) GetAppInstanceVip(vip string) (Applications, error)

查询vip下的实例 GET {{url}}/eureka/vips/{{vipAddress}}

func (*Client) GetAppInstances

func (c *Client) GetAppInstances(appID string) (Application, error)

获取指定服务的实例 GET {{url}}/eureka/apps/{{appID}}

func (*Client) GetApps

func (c *Client) GetApps() (Applications, error)

获取所有实例 GET {{url}}/eureka/apps

func (*Client) GetOwnAppInstance

func (c *Client) GetOwnAppInstance() (Instance, error)

查询自己注册的服务信息 GET {{url}}/eureka/apps/{{appID}}/{{appID}}:{{instanceID}}

func (*Client) GetOwnAppInstances

func (c *Client) GetOwnAppInstances() (Application, error)

查询同服务的所有实例 GET {{url}}/eureka/apps/{{appID}}

func (*Client) Register

func (c *Client) Register() error

注册上线 POST {{url}}/eureka/apps/{{appID}}

func (*Client) Request

func (c *Client) Request(serviceName string, req *http.Request) ([]byte, error)

通过request装饰器请求其他服务

func (*Client) RoundTrip

func (c *Client) RoundTrip(r *http.Request) (*http.Response, error)

func (*Client) UpdateOwnAppInstanceMetadata

func (c *Client) UpdateOwnAppInstanceMetadata(value map[string]string) error

更新元数据 {{url}}/eureka/v2/apps/{{appID}}/{{instanceID}}/metadata?key=value

func (*Client) UpdateOwnAppInstanceStatus

func (c *Client) UpdateOwnAppInstanceStatus(status InstanceStatus) error

更改自己实例状态 PUT {{url}}/eureka/apps/{{appID}}/{{instanceID}}/status?value=OUT_OF_SERVICE

type DataCenterInfo

type DataCenterInfo struct {
	Class string `json:"@class" xml:"class,attr"`
	Name  string `json:"name" xml:"name"`
}

type DataCenterInfoName

type DataCenterInfoName string

type Instance

type Instance struct {
	InstanceID                    string         `json:"instanceId" xml:"instanceId"`
	App                           string         `json:"app" xml:"app"`
	HostName                      string         `json:"hostName" xml:"hostName"`
	IpAddr                        string         `json:"ipAddr" xml:"ipAddr"`
	Sid                           string         `json:"sid" xml:"sid"` //default:na
	HomePageUrl                   string         `json:"homePageUrl" xml:"homePageUrl"`
	StatusPageUrl                 string         `json:"statusPageUrl" xml:"statusPageUrl"`
	HealthCheckUrl                string         `json:"healthCheckUrl" xml:"healthCheckUrl"`
	VipAddress                    string         `json:"vipAddress" xml:"vipAddress"`
	SecureVipAddress              string         `json:"secureVipAddress" xml:"secureVipAddress"`
	CountryId                     int            `json:"countryId" xml:"countryId"` // 	US:1
	DataCenterInfo                DataCenterInfo `json:"dataCenterInfo" xml:"dataCenterInfo"`
	Status                        InstanceStatus `json:"status" xml:"status"`
	Overriddenstatus              InstanceStatus `json:"overriddenstatus" xml:"overriddenstatus"`
	LeaseInfo                     LeaseInfo      `json:"leaseInfo" xml:"leaseInfo"`
	IsCoordinatingDiscoveryServer bool           `json:"isCoordinatingDiscoveryServer" xml:"isCoordinatingDiscoveryServer"`
	LastUpdatedTimestamp          int64          `json:"lastUpdatedTimestamp" xml:"lastUpdatedTimestamp"`
	LastDirtyTimestamp            int64          `json:"lastDirtyTimestamp" xml:"lastDirtyTimestamp"`
	ActionType                    ActionType     `json:"actionType" xml:"actionType"`
	Port                          Port           `json:"port" xml:"port"`             //7001 $7001 @enabled=true
	SecurePort                    Port           `json:"securePort" xml:"securePort"` //7002 $7002 @enabled=false
	Metadata                      interface{}    `json:"metadata,omitempty" xml:"metadata"`
}

type InstanceStatus

type InstanceStatus string
const (
	UP             InstanceStatus = "UP"
	DOWN           InstanceStatus = "DOWN"
	STARTING       InstanceStatus = "STARTING"
	OUT_OF_SERVICE InstanceStatus = "OUT_OF_SERVICE"
	UNKNOWN        InstanceStatus = "UNKNOWN"
)

type LeaseInfo

type LeaseInfo struct {
	RenewalIntervalInSecs int   `json:"renewalIntervalInSecs" xml:"renewalIntervalInSecs"` //30
	DurationInSecs        int   `json:"durationInSecs" xml:"durationInSecs"`               //90
	RegistrationTimestamp int64 `json:"registrationTimestamp" xml:"registrationTimestamp"`
	LastRenewalTimestamp  int64 `json:"lastRenewalTimestamp" xml:"lastRenewalTimestamp"`
	EvictionTimestamp     int64 `json:"evictionTimestamp" xml:"evictionTimestamp"`
	ServiceUpTimestamp    int64 `json:"serviceUpTimestamp" xml:"serviceUpTimestamp"`
}

type MaxRetriesExceeded

type MaxRetriesExceeded struct {
	Description string
	MaxRetries  int
}

MaxRetriesExceeded is an error that occurs when the maximum amount of retries is exceeded.

func (MaxRetriesExceeded) Error

func (err MaxRetriesExceeded) Error() string

type Port

type Port struct {
	Enabled bool `json:"@enabled" xml:"enabled,attr"`
	Value   int  `json:"$" xml:",chardata"`
}

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL