|
|
|
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{}
|
|
|
|
|
|
|
|
// GetClient @Title 获取RPC客户的
|
|
|
|
func GetClient(s interface{}) client.XClient {
|
|
|
|
key := reflect.ValueOf(s).Elem().Type().String()
|
|
|
|
xClient, ok := mClient.Load(key)
|
|
|
|
if !ok {
|
|
|
|
mutex.Lock()
|
|
|
|
xClient, ok = mClient.Load(key)
|
|
|
|
if !ok {
|
|
|
|
split := strings.Split(reflect.ValueOf(s).Elem().Type().String(), ".")
|
|
|
|
servicePath := strings.ToUpper(split[1][0:1]) + split[1][1:]
|
|
|
|
|
|
|
|
d, err := client.NewConsulDiscovery(split[0], 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 {
|
|
|
|
servicePath := strings.ToUpper(service[0:1]) + service[1:]
|
|
|
|
|
|
|
|
d, err := client.NewConsulDiscovery(base, 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)
|
|
|
|
}
|