balance.go 1.8 KB
Newer Older
Y
Your Name 已提交
1
package balancemanager
E
eoLinker API Management 已提交
2 3 4

import (
	"encoding/json"
黄孟柱 已提交
5 6 7 8 9 10 11 12
	log "github.com/eolinker/goku-api-gateway/goku-log"
	"github.com/eolinker/goku-api-gateway/goku-node/manager/updater"
	node_common "github.com/eolinker/goku-api-gateway/goku-node/node-common"
	"github.com/eolinker/goku-api-gateway/goku-service/application"
	"github.com/eolinker/goku-api-gateway/goku-service/balance"
	dao_balance "github.com/eolinker/goku-api-gateway/server/dao/node-mysql/dao-balance"
	"github.com/eolinker/goku-api-gateway/server/driver"
	entity "github.com/eolinker/goku-api-gateway/server/entity/node-entity"
E
eoLinker API Management 已提交
13 14 15 16 17 18 19
	"strings"
)

func init() {
	updater.Add(loadBalanceInfo, 3, "goku_balance")
}

Y
Your Name 已提交
20
//Get get
E
eoLinker API Management 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
func Get(name string) (application.IHttpApplication, bool) {

	return balance.GetByName(name)
}

// 加载负载均衡信息
func loadBalanceInfo() {

	balanceList, err := getAllBalance()
	if err != nil {
		log.Info(err)
		return
	}

	balance.ResetBalances(balanceList)
}
func genBalance(e *entity.Balance) *balance.Balance {
	b := &balance.Balance{
		Name:      e.Name,
		Discovery: e.ServiceName,
		AppConfig: "",
	}

	switch e.ServiceType {
	case driver.Static:
		{
			var m map[string]string
			b.AppConfig = e.Static
			if err := json.Unmarshal([]byte(e.StaticCluster), &m); err == nil {
				if v, has := m[node_common.ClusterName()]; has {
Y
Your Name 已提交
51
					if len(strings.Trim(v, " ")) > 0 {
E
eoLinker API Management 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
						b.AppConfig = v
					}
				}
			}
			return b
		}
	case driver.Discovery:
		{
			b.AppConfig = e.AppName
			return b
		}

	}
	return nil
}
func getAllBalance() ([]*balance.Balance, error) {

	entities, e := dao_balance.GetAllBalance()
	if e != nil {
		return nil, e
	}
	infos := make([]*balance.Balance, 0, len(entities))

	for _, ent := range entities {
		b := genBalance(ent)
		if b != nil {
			infos = append(infos, b)
		}
	}
	return infos, nil
}