You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
2.0 KiB
82 lines
2.0 KiB
package client
|
|
|
|
import (
|
|
"fmt"
|
|
"git.oa00.com/supply-chain/service/config"
|
|
"github.com/smallnest/rpcx/client"
|
|
"log"
|
|
"reflect"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
var mClient = sync.Map{}
|
|
var mutex = sync.Mutex{}
|
|
var basePkgPath string
|
|
|
|
type empty int
|
|
|
|
func init() {
|
|
pkgPath := reflect.TypeOf(empty(0)).PkgPath()
|
|
basePkgPath = pkgPath[:len(pkgPath)-6]
|
|
}
|
|
|
|
// GetClient @Title 获取RPC客户的
|
|
func GetClient(s interface{}) client.XClient {
|
|
path := strings.TrimPrefix(reflect.ValueOf(s).Elem().Type().PkgPath(), basePkgPath)
|
|
actionName := reflect.ValueOf(s).Elem().Type().Name()
|
|
key := path + "/" + actionName
|
|
xClient, ok := mClient.Load(key)
|
|
if !ok {
|
|
mutex.Lock()
|
|
xClient, ok = mClient.Load(key)
|
|
if !ok {
|
|
split := strings.SplitN(key, "/", 2)
|
|
basePath := split[0]
|
|
servicePath := split[1]
|
|
|
|
d, err := client.NewConsulDiscovery(basePath, servicePath, config.RpcConfig.RegistryServer, nil)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return nil
|
|
}
|
|
option := client.DefaultOption
|
|
option.Retries = 3
|
|
option.GenBreaker = func() client.Breaker {
|
|
return client.NewConsecCircuitBreaker(2, 30*time.Second)
|
|
}
|
|
xClient = client.NewXClient(servicePath, client.Failover, client.RoundRobin, d, option)
|
|
mClient.Store(key, xClient)
|
|
}
|
|
mutex.Unlock()
|
|
}
|
|
return xClient.(client.XClient)
|
|
}
|
|
|
|
// GetClientName @Title 根据服务名获取客户端
|
|
func GetClientName(base, service string) client.XClient {
|
|
key := fmt.Sprintf("%s/%s", base, service)
|
|
xClient, ok := mClient.Load(key)
|
|
if !ok {
|
|
mutex.Lock()
|
|
xClient, ok = mClient.Load(key)
|
|
if !ok {
|
|
d, err := client.NewConsulDiscovery(base, service, config.RpcConfig.RegistryServer, nil)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return nil
|
|
}
|
|
option := client.DefaultOption
|
|
option.Retries = 3
|
|
option.GenBreaker = func() client.Breaker {
|
|
return client.NewConsecCircuitBreaker(2, 30*time.Second)
|
|
}
|
|
xClient = client.NewXClient(service, client.Failover, client.RoundRobin, d, option)
|
|
mClient.Store(key, xClient)
|
|
}
|
|
mutex.Unlock()
|
|
}
|
|
return xClient.(client.XClient)
|
|
}
|