初始化项目
This commit is contained in:
63
trunk/goutil/grpc-util/client/client.go
Normal file
63
trunk/goutil/grpc-util/client/client.go
Normal 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
|
||||
}
|
||||
8
trunk/goutil/grpc-util/client/doc.go
Normal file
8
trunk/goutil/grpc-util/client/doc.go
Normal file
@@ -0,0 +1,8 @@
|
||||
// ************************************
|
||||
// @package: client
|
||||
// @description: grpc客户端辅助包
|
||||
// @author: byron
|
||||
// @revision history:
|
||||
// @create date: 2022-01-19 16:50:24
|
||||
// ************************************
|
||||
package client
|
||||
29
trunk/goutil/grpc-util/client/readme.md
Normal file
29
trunk/goutil/grpc-util/client/readme.md
Normal 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
|
||||
Reference in New Issue
Block a user