服务之间相互调用

This commit is contained in:
2026-08-24 10:06:52 +08:00
parent c33fbdb422
commit 80f428c032
49 changed files with 1756 additions and 35 deletions
+117
View File
@@ -237,6 +237,123 @@ func NewServiceContext(c config.Config, db *gorm.DB) *ServiceContext {
```
编辑2调用其它服务 `internal/svc/servicecontext.go`
```go
import (
"fmt"
"net"
"strconv"
"sync"
"time"
"lone-services/pkg/discovery"
"lone-services/pkg/utils"
"lone-services/services/order/internal/config"
"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
ExpressSvcName string //服务名
}
func NewServiceContext(c config.Config, db *gorm.DB) *ServiceContext {
//启动仅读取配置,不建立rpc连接 多个服务就多个
expressSvc := utils.GetConfigString("services.express")
if expressSvc == utils.StringEmpty {
logx.Error("config services.express empty")
}
svcCtx := &ServiceContext{
Config: c,
DB: db,
Prefix: utils.GetConfigString("mysql.prefix"),
ExpressSvcName: expressSvc,
}
return svcCtx
}
调用方法logic中
//调用其它服务实例
//cli, err := svc.GetRpcClient(l.svcCtx.ExpressSvcName)
//if err != nil {
// l.Logger.Errorf("get express rpc err: %v", err)
// //降级逻辑
// return l.out(utils.ErrorInternalServer, "express"+utils.ErrorInternalServer.Msg)
//}
//expClient := express.NewExpressClient(cli.Conn())
//res, _ := expClient.Ping(context.Background(), &express.Request{})
//l.Logger.Error("res: %v", res)
```
### 7. 接入 Docker Compose
`deploy/docker-compose.override.yml` 增加服务: