feat(pool): 添加基于BadgerDB的连接池实现
- 新增BadgerPool结构体,支持WebSocket和TCP连接类型 - 实现连接的增删改查功能,包括内存缓存机制提升性能 - 添加按类型查询连接、统计连接数量等辅助方法 - 实现清理非活跃连接的功能,支持定期维护 - 更新示例代码以处理初始化错误并改进错误处理 - 添加BadgerDB依赖及其相关间接依赖包
This commit is contained in:
+5
-1
@@ -18,7 +18,11 @@ func Example() {
|
||||
}
|
||||
|
||||
// 创建TCP服务器
|
||||
server := NewTCPServer("0.0.0.0:8888", config)
|
||||
server, err := NewTCPServer("0.0.0.0:8888", config)
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to create server: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 设置消息处理函数
|
||||
server.SetMessageHandler(func(conn *TcpConnection, msg *TcpMessage) error {
|
||||
|
||||
+78
-4
@@ -6,6 +6,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.magicany.cc/black1552/gf-common/pool"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/net/gtcp"
|
||||
"github.com/gogf/gf/v2/os/glog"
|
||||
@@ -32,18 +33,26 @@ type TCPServer struct {
|
||||
// ConnectionPool 连接池结构
|
||||
type ConnectionPool struct {
|
||||
connections map[string]*TcpConnection
|
||||
badgerPool *pool.BadgerPool
|
||||
mutex sync.RWMutex
|
||||
config *TcpPoolConfig
|
||||
logger *glog.Logger
|
||||
}
|
||||
|
||||
// NewTCPServer 创建一个新的TCP服务器
|
||||
func NewTCPServer(address string, config *TcpPoolConfig) *TCPServer {
|
||||
func NewTCPServer(address string, config *TcpPoolConfig) (*TCPServer, error) {
|
||||
logger := g.Log(address)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
// 初始化BadgerDB连接池
|
||||
badgerPool, err := pool.NewBadgerPool()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create badger pool: %w", err)
|
||||
}
|
||||
|
||||
pool := &ConnectionPool{
|
||||
connections: make(map[string]*TcpConnection),
|
||||
badgerPool: badgerPool,
|
||||
config: config,
|
||||
logger: logger,
|
||||
}
|
||||
@@ -58,7 +67,7 @@ func NewTCPServer(address string, config *TcpPoolConfig) *TCPServer {
|
||||
}
|
||||
|
||||
server.Listener = gtcp.NewServer(address, server.handleConnection)
|
||||
return server
|
||||
return server, nil
|
||||
}
|
||||
|
||||
// SetMessageHandler 设置消息处理函数
|
||||
@@ -86,6 +95,11 @@ func (s *TCPServer) Stop() error {
|
||||
s.Listener.Close()
|
||||
s.wg.Wait()
|
||||
s.Connection.Clear()
|
||||
// 关闭BadgerDB连接池
|
||||
if err := s.Connection.badgerPool.Close(); err != nil {
|
||||
s.Logger.Error(s.ctx, fmt.Sprintf("Failed to close BadgerDB pool: %v", err))
|
||||
// 不影响服务器停止,仅记录错误
|
||||
}
|
||||
s.Logger.Info(s.ctx, "TCP server stopped")
|
||||
return nil
|
||||
}
|
||||
@@ -109,6 +123,23 @@ func (s *TCPServer) handleConnection(conn *gtcp.Conn) {
|
||||
s.Connection.Add(tcpConn)
|
||||
s.Logger.Info(s.ctx, fmt.Sprintf("New connection established: %s", connID))
|
||||
|
||||
// 存储到BadgerDB
|
||||
connInfo := &pool.ConnectionInfo{
|
||||
ID: connID,
|
||||
Type: pool.ConnTypeTCP,
|
||||
Address: conn.RemoteAddr().String(),
|
||||
IsActive: true,
|
||||
LastUsed: time.Now(),
|
||||
CreatedAt: time.Now(),
|
||||
Data: map[string]interface{}{
|
||||
"localAddress": conn.LocalAddr().String(),
|
||||
},
|
||||
}
|
||||
if err := s.Connection.badgerPool.Add(connInfo); err != nil {
|
||||
s.Logger.Error(s.ctx, fmt.Sprintf("Failed to store connection to BadgerDB: %v", err))
|
||||
// 不影响连接建立,仅记录错误
|
||||
}
|
||||
|
||||
// 启动消息接收协程
|
||||
go s.receiveMessages(tcpConn)
|
||||
}
|
||||
@@ -121,6 +152,11 @@ func (s *TCPServer) receiveMessages(conn *TcpConnection) {
|
||||
}
|
||||
s.Connection.Remove(conn.Id)
|
||||
conn.Server.Close()
|
||||
// 从BadgerDB移除
|
||||
if err := s.Connection.badgerPool.Remove(conn.Id); err != nil {
|
||||
s.Logger.Error(s.ctx, fmt.Sprintf("Failed to remove connection from BadgerDB: %v", err))
|
||||
// 不影响连接关闭,仅记录错误
|
||||
}
|
||||
s.Logger.Info(s.ctx, fmt.Sprintf("Connection closed: %s", conn.Id))
|
||||
}()
|
||||
|
||||
@@ -142,10 +178,21 @@ func (s *TCPServer) receiveMessages(conn *TcpConnection) {
|
||||
|
||||
if n > 0 {
|
||||
// 更新最后使用时间
|
||||
now := time.Now()
|
||||
conn.Mutex.Lock()
|
||||
conn.LastUsed = time.Now()
|
||||
conn.LastUsed = now
|
||||
conn.Mutex.Unlock()
|
||||
|
||||
// 更新BadgerDB中的连接信息
|
||||
connInfo, err := s.Connection.badgerPool.Get(conn.Id)
|
||||
if err == nil && connInfo != nil {
|
||||
connInfo.LastUsed = now
|
||||
if err := s.Connection.badgerPool.Update(connInfo); err != nil {
|
||||
s.Logger.Error(s.ctx, fmt.Sprintf("Failed to update connection in BadgerDB: %v", err))
|
||||
// 不影响消息处理,仅记录错误
|
||||
}
|
||||
}
|
||||
|
||||
// 处理消息
|
||||
data := make([]byte, n)
|
||||
copy(data, buffer[:n])
|
||||
@@ -209,7 +256,19 @@ func (s *TCPServer) sendMessage(conn *TcpConnection, data []byte) error {
|
||||
}
|
||||
|
||||
// 更新最后使用时间
|
||||
conn.LastUsed = time.Now()
|
||||
now := time.Now()
|
||||
conn.LastUsed = now
|
||||
|
||||
// 更新BadgerDB中的连接信息
|
||||
connInfo, err := s.Connection.badgerPool.Get(conn.Id)
|
||||
if err == nil && connInfo != nil {
|
||||
connInfo.LastUsed = now
|
||||
if err := s.Connection.badgerPool.Update(connInfo); err != nil {
|
||||
s.Logger.Error(s.ctx, fmt.Sprintf("Failed to update connection in BadgerDB: %v", err))
|
||||
// 不影响消息发送,仅记录错误
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -224,11 +283,21 @@ func (s *TCPServer) Kick(connID string) error {
|
||||
conn.Server.Close()
|
||||
// 从连接池移除
|
||||
s.Connection.Remove(connID)
|
||||
// 从BadgerDB移除
|
||||
if err := s.Connection.badgerPool.Remove(connID); err != nil {
|
||||
s.Logger.Error(s.ctx, fmt.Sprintf("Failed to remove connection from BadgerDB: %v", err))
|
||||
// 不影响连接关闭,仅记录错误
|
||||
}
|
||||
|
||||
s.Logger.Info(s.ctx, fmt.Sprintf("Kicked connection: %s", connID))
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAllConnIDs 获取所有在线连接的ID列表
|
||||
func (s *TCPServer) GetAllConnIDs() ([]string, error) {
|
||||
return s.Connection.GetAllConnIDs()
|
||||
}
|
||||
|
||||
// Add 添加连接到连接池
|
||||
func (p *ConnectionPool) Add(conn *TcpConnection) {
|
||||
p.mutex.Lock()
|
||||
@@ -278,3 +347,8 @@ func (p *ConnectionPool) Count() int {
|
||||
defer p.mutex.RUnlock()
|
||||
return len(p.connections)
|
||||
}
|
||||
|
||||
// GetAllConnIDs 获取所有在线连接的ID列表
|
||||
func (p *ConnectionPool) GetAllConnIDs() ([]string, error) {
|
||||
return p.badgerPool.GetAllConnIDs()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user