109 lines
2.2 KiB
Go
109 lines
2.2 KiB
Go
// Package rpc ...
|
|
//
|
|
// Description : rpc ...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 2022-06-29 15:21
|
|
package rpc
|
|
|
|
import (
|
|
"errors"
|
|
"sync"
|
|
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
var (
|
|
// Request 请求实例
|
|
Request *request
|
|
)
|
|
|
|
// InitRPC 初始化RPC服务
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 15:23 2022/6/29
|
|
func InitRPC(serviceTable map[string]*Service, loggerInstance *zap.Logger) error {
|
|
if nil == serviceTable {
|
|
serviceTable = make(map[string]*Service)
|
|
}
|
|
for _, item := range serviceTable {
|
|
if item.ApiTable == nil {
|
|
item.ApiTable = make(map[string]*Api)
|
|
}
|
|
}
|
|
Request = &request{
|
|
logger: loggerInstance,
|
|
serviceTable: serviceTable,
|
|
lock: &sync.RWMutex{},
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type request struct {
|
|
logger *zap.Logger
|
|
serviceTable map[string]*Service
|
|
lock *sync.RWMutex
|
|
}
|
|
|
|
// AddService 新增一个服务
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 17:13 2022/6/29
|
|
func (r *request) AddService(serviceInfo *Service) error {
|
|
if nil == serviceInfo {
|
|
return errors.New("service info is nil")
|
|
}
|
|
r.lock.Lock()
|
|
defer r.lock.Unlock()
|
|
if _, exist := r.serviceTable[serviceInfo.Flag]; exist {
|
|
return errors.New(serviceInfo.Flag + " already exist")
|
|
}
|
|
r.serviceTable[serviceInfo.Flag] = serviceInfo
|
|
return nil
|
|
}
|
|
|
|
// GetServiceInfo ...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 11:32 2022/6/30
|
|
func (r *request) GetServiceInfo(serviceFlag string) (*Service, error) {
|
|
var (
|
|
serviceInfo *Service
|
|
exist bool
|
|
)
|
|
|
|
r.lock.RLock()
|
|
defer r.lock.Unlock()
|
|
if serviceInfo, exist = r.serviceTable[serviceFlag]; !exist {
|
|
return nil, errors.New(serviceFlag + " -> 服务不存在")
|
|
}
|
|
return serviceInfo, nil
|
|
}
|
|
|
|
// AddServiceApi 向一个service中增加Api
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 11:26 2022/6/30
|
|
func (r *request) AddServiceApi(serviceFlag string, apiConfig *Api) error {
|
|
var (
|
|
serviceInfo *Service
|
|
err error
|
|
)
|
|
|
|
if serviceInfo, err = r.GetServiceInfo(serviceFlag); nil != err {
|
|
return err
|
|
}
|
|
r.lock.Lock()
|
|
defer r.lock.Unlock()
|
|
if nil == serviceInfo.ApiTable {
|
|
serviceInfo.ApiTable = make(map[string]*Api)
|
|
}
|
|
serviceInfo.ApiTable[apiConfig.Flag] = apiConfig
|
|
return nil
|
|
}
|