初始化项目

This commit is contained in:
皮蛋13361098506
2025-01-06 16:01:02 +08:00
commit 1b77f62820
575 changed files with 69193 additions and 0 deletions

View File

@@ -0,0 +1,63 @@
package client
import (
"context"
"sync"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
var (
// 缓存连接 key:rpc地址 value:连接指针对象
rpcConMap sync.Map
// 连接超时时间
defaultTimeOut = time.Second * 1
)
// GetClientConn
// @description: 获取grpc连接对象
// parameter:
// @rpcAddres:连接地址
// return:
// @*grpc.ClientConn:连接对象
// @error:错误对象
func GetClientConn(rpcAddres string) (*grpc.ClientConn, error) {
// 从缓存获取
if con1, isok := rpcConMap.Load(rpcAddres); isok {
return con1.(*grpc.ClientConn), nil
}
// 构造新对象
//ctx, _ := context.WithDeadline(context.Background(), time.Now().Add(time.Second*1))
var ctx, _ = context.WithTimeout(context.Background(), defaultTimeOut)
con, err := grpc.DialContext(ctx, rpcAddres, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return nil, err
}
// 加入缓存
rpcConMap.Store(rpcAddres, con)
return con, nil
}
// ClearClientConn
// @description: 根据连接地址,删除缓存的连接对象
// parameter:
// @rpcAddres:连接地址
// return:
func ClearClientConn(rpcAddres string) {
rpcConMap.Delete(rpcAddres)
}
// SetDefaultTimeOut
// @description: 设置连接的默认超时
// parameter:
// @outTime:超时时间
// return:
func SetDefaultTimeOut(outTime time.Duration) {
defaultTimeOut = outTime
}

View File

@@ -0,0 +1,8 @@
// ************************************
// @package: client
// @description: grpc客户端辅助包
// @author: byron
// @revision history:
// @create date: 2022-01-19 16:50:24
// ************************************
package client

View File

@@ -0,0 +1,29 @@
client简单封装了grpc相关调用方法缓存了connection连接
整体文档入口请参考:[传送门](../readme.md)
## 使用方式如下:
### 1.导入包
```go
import (
"vast.com/goutil/grpc-util/client"
)
```
### 2.获取连接
```go
con, err := client.GetClientConn(host)
```
### 3.清理某个连接
```go
client.ClearClientConn("ip:port")
```
### 4.设置连接的默认超时时间
```go
client.SetDefaultTimeOut(time.Second * 3)
```
注意:
1.设置后对后续创建的连接生效,已经创建的不生效
2.默认的超时 时间为1s