重命名客户端相关术语为节点;移动 utils 包到根路径;优化网关对节点各种连接状态的处理,并在节点断联后统一清理资源
This commit is contained in:
44
utils/sync.go
Normal file
44
utils/sync.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
type WaitGroup interface {
|
||||
Add(delta int)
|
||||
Done()
|
||||
Wait()
|
||||
}
|
||||
|
||||
type CountWaitGroup struct {
|
||||
wg sync.WaitGroup
|
||||
num atomic.Int64
|
||||
}
|
||||
|
||||
func (c *CountWaitGroup) Add(delta int) {
|
||||
c.wg.Add(delta)
|
||||
c.num.Add(int64(delta))
|
||||
}
|
||||
|
||||
func (c *CountWaitGroup) Done() {
|
||||
c.wg.Done()
|
||||
c.num.Add(-1)
|
||||
}
|
||||
|
||||
func (c *CountWaitGroup) Wait() {
|
||||
c.wg.Wait()
|
||||
}
|
||||
|
||||
func (c *CountWaitGroup) Count() uint64 {
|
||||
return uint64(c.num.Load())
|
||||
}
|
||||
|
||||
func WgWait[T WaitGroup](wg T) <-chan struct{} {
|
||||
ch := make(chan struct{})
|
||||
go func() {
|
||||
wg.Wait()
|
||||
ch <- struct{}{}
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
36
utils/utils.go
Normal file
36
utils/utils.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log/slog"
|
||||
)
|
||||
|
||||
func ReadByte(reader io.Reader) (byte, error) {
|
||||
buffer, err := ReadBuffer(reader, 1)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return buffer[0], nil
|
||||
}
|
||||
|
||||
func ReadBuffer(reader io.Reader, size int) ([]byte, error) {
|
||||
if size == 0 {
|
||||
return []byte{}, nil
|
||||
}
|
||||
buffer := make([]byte, size)
|
||||
_, err := io.ReadFull(reader, buffer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return buffer, nil
|
||||
}
|
||||
|
||||
// Close 关闭对象,传入值绝对不能为 nil
|
||||
func Close[T io.Closer](v T) {
|
||||
err := v.Close()
|
||||
if err != nil {
|
||||
slog.Warn("对象关闭失败", "err", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user