manager.go 1.3 KB
Newer Older
Y
Your Name 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
package diting

import (
	"fmt"
	"github.com/eolinker/goku-api-gateway/ksitigarbha"
)

var (
	constructorMap = make(map[string]Constructor)
	refresher      = NewRefreshers()
)

//Register register
func Register(namespace string, constructor Constructor) {

	_, has := constructorMap[namespace]
	if has {
		panic(fmt.Sprint("duplicate namespace of constructor by", namespace))
	}
	constructorMap[namespace] = constructor

}

func get(namespace string) (Constructor, bool) {

	constructor, has := constructorMap[namespace]
	return constructor, has

}

func construct(confs map[string]string) Factories {

Y
Your Name 已提交
33
	lives:= make(map[string]int)
Y
Your Name 已提交
34 35 36
	factories := make(Factories,0,len(confs))
	defer func() {
		// close 关闭不用的模块
Y
Your Name 已提交
37

Y
Your Name 已提交
38
		for name,constructor:= range constructorMap{
Y
Your Name 已提交
39

Y
Your Name 已提交
40 41 42 43 44 45 46 47 48 49
			if _,has:=lives[name];!has{
				constructor.Close()
			}
		}
	}()
	if confs == nil{
		return factories
	}

	for name, conf := range confs {
Y
Your Name 已提交
50 51
		namespace,_:=ksitigarbha.GetNameSpaceByName(name)
		lives[namespace] = 1
Y
Your Name 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
		constructor, has := get(namespace)
		if !has {
			continue
		}

		factory, err := constructor.Create(conf)
		if err != nil {
			continue
		}

		factories = append(factories, factory)
	}
	return factories
}

//Refresh refresh
func Refresh(confs map[string]string) {
	factories := construct(confs)
	refresher.Refresh(factories)
}