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.
service/client/client.go

82 lines
2.1 KiB

2 years ago
package client
import (
"errors"
"fmt"
2 years ago
"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]
}
2 years ago
// GetClient @Title 获取RPC客户的
func GetClient(s interface{}) (client.XClient, error) {
path := strings.TrimPrefix(reflect.ValueOf(s).Elem().Type().PkgPath(), basePkgPath)
actionName := reflect.ValueOf(s).Elem().Type().Name()
key := path + "/" + actionName
2 years ago
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]
2 years ago
d, err := client.NewConsulDiscovery(basePath, servicePath, config.RpcConfig.RegistryServer, nil)
2 years ago
if err != nil {
return nil, errors.New("系统异常")
2 years ago
}
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), nil
2 years ago
}
// GetClientName @Title 根据服务名获取客户端
func GetClientName(base, service string) (client.XClient, error) {
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, errors.New("系统异常")
}
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), nil
}