Files
lone-services/services/express/internal/svc/servicecontext.go
T
gjs f84799c3c4
CI / changes (push) Successful in 38s
CI / ad (push) Successful in 29s
CI / admin (push) Successful in 22s
CI / bff (push) Successful in 19s
CI / chore (push) Successful in 22s
CI / equipment (push) Successful in 20s
CI / express (push) Successful in 18s
CI / log (push) Successful in 0s
CI / product (push) Successful in 15s
CI / sale (push) Successful in 16s
CI / task (push) Successful in 17s
CI / user (push) Successful in 16s
CI / wecom (push) Successful in 16s
add log service and change order
2026-09-03 17:04:25 +08:00

99 lines
2.2 KiB
Go

package svc
import (
"fmt"
"lone-services/pkg/discovery"
"lone-services/pkg/utils"
"lone-services/services/express/internal/config"
"net"
"strconv"
"sync"
"time"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/zrpc"
"gorm.io/gorm"
)
type rpcClientCacheEntry struct {
cli zrpc.Client
target string
expireAt time.Time
}
const rpcClientCacheTTL = 30 * time.Second //缓存过期时间
var (
rpcCacheLock sync.Mutex
rpcCache = make(map[string]*rpcClientCacheEntry)
)
func GetRpcClient(serviceName string) (zrpc.Client, error) {
if serviceName == utils.StringEmpty {
err := fmt.Errorf("rpc serviceName is empty")
logx.Error(err)
return nil, err
}
cacheKey := serviceName
rpcCacheLock.Lock()
entry, ok := rpcCache[cacheKey]
if ok && time.Now().Before(entry.expireAt) {
rpcCacheLock.Unlock()
return entry.cli, nil
}
delete(rpcCache, cacheKey)
rpcCacheLock.Unlock()
inst, err := discovery.Pick(serviceName)
if err != nil {
err = fmt.Errorf("discovery pick %s failed: %w", serviceName, err)
logx.Error(err)
return nil, err
}
target := net.JoinHostPort(inst.IP, strconv.FormatUint(inst.Port, utils.NumberTen))
cli := zrpc.MustNewClient(zrpc.RpcClientConf{
Target: target,
Timeout: utils.RpcTimeOut, //rpc调用超时5s
})
rpcCacheLock.Lock()
rpcCache[cacheKey] = &rpcClientCacheEntry{
cli: cli,
target: target,
expireAt: time.Now().Add(rpcClientCacheTTL),
}
rpcCacheLock.Unlock()
return cli, nil
}
type ServiceContext struct {
Config config.Config
DB *gorm.DB
Prefix string
ProductSvcName string //服务名
OrderSvcName string
}
func NewServiceContext(c config.Config, db *gorm.DB) *ServiceContext {
productSvc := utils.GetConfigString("services.product")
orderSvc := utils.GetConfigString("services.order")
if productSvc == utils.StringEmpty {
logx.Error("config services.product empty")
}
if orderSvc == utils.StringEmpty {
logx.Error("config services.order empty")
}
return &ServiceContext{
Config: c,
DB: db,
Prefix: utils.GetConfigString("mysql.prefix"),
ProductSvcName: productSvc,
OrderSvcName: orderSvc,
}
}