feat(pool): 添加SQLite连接池实现并集成到TCP和WebSocket服务
- 新增pool包,包含ConnType连接类型和ConnectionInfo连接信息结构体 - 实现SQLitePool连接池,支持添加、获取、删除、更新连接操作 - 为TCP服务器集成SQLite连接池,存储连接信息到数据库 - 为WebSocket管理器集成SQLite连接池,存储连接信息到数据库 - 在TCP和WebSocket的连接生命周期中同步更新SQLite连接状态 - 添加GetAllConnIDs方法获取所有在线连接ID列表 - 在示例代码中添加错误处理和测试功能
This commit is contained in:
+50
-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 {
|
||||
@@ -45,3 +49,48 @@ func Example() {
|
||||
|
||||
fmt.Println("TCP server stopped.")
|
||||
}
|
||||
|
||||
// TestTCP 测试TCP连接
|
||||
func TestTCP() {
|
||||
fmt.Println("=== 测试TCP连接 ===")
|
||||
fmt.Println("1. 创建TCP服务器配置")
|
||||
config := &TcpPoolConfig{
|
||||
BufferSize: 2048,
|
||||
MaxConnections: 100000,
|
||||
ConnectTimeout: time.Second * 5,
|
||||
ReadTimeout: time.Second * 30,
|
||||
WriteTimeout: time.Second * 10,
|
||||
MaxIdleTime: time.Minute * 5,
|
||||
}
|
||||
fmt.Println("2. 创建TCP服务器")
|
||||
server, err := NewTCPServer("0.0.0.0:8888", config)
|
||||
if err != nil {
|
||||
fmt.Printf("创建服务器失败:%v\n", err)
|
||||
return
|
||||
}
|
||||
fmt.Println("3. 服务器创建成功")
|
||||
fmt.Println("4. 获取在线连接数")
|
||||
count := server.Connection.Count()
|
||||
fmt.Printf("当前在线连接数:%d\n", count)
|
||||
fmt.Println("5. 获取所有在线连接ID")
|
||||
connIDs, err := server.GetAllConnIDs()
|
||||
if err != nil {
|
||||
fmt.Printf("获取在线连接ID失败:%v\n", err)
|
||||
} else {
|
||||
fmt.Printf("在线连接ID:%v\n", connIDs)
|
||||
}
|
||||
fmt.Println("6. 启动服务器")
|
||||
if err := server.Start(); err != nil {
|
||||
fmt.Printf("启动服务器失败:%v\n", err)
|
||||
return
|
||||
}
|
||||
fmt.Println("7. 服务器启动成功,运行2秒后停止")
|
||||
time.Sleep(time.Second * 2)
|
||||
fmt.Println("8. 停止服务器")
|
||||
if err := server.Stop(); err != nil {
|
||||
fmt.Printf("停止服务器失败:%v\n", err)
|
||||
} else {
|
||||
fmt.Println("服务器停止成功")
|
||||
}
|
||||
fmt.Println("=== TCP测试完成 ===")
|
||||
}
|
||||
|
||||
+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
|
||||
sqlitePool *pool.SQLitePool
|
||||
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())
|
||||
|
||||
// 初始化SQLite连接池
|
||||
sqlitePool, err := pool.NewSQLitePool()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create sqlite pool: %w", err)
|
||||
}
|
||||
|
||||
pool := &ConnectionPool{
|
||||
connections: make(map[string]*TcpConnection),
|
||||
sqlitePool: sqlitePool,
|
||||
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()
|
||||
// 关闭SQLite连接池
|
||||
if err := s.Connection.sqlitePool.Close(); err != nil {
|
||||
s.Logger.Error(s.ctx, fmt.Sprintf("Failed to close SQLite 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))
|
||||
|
||||
// 存储到SQLite
|
||||
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.sqlitePool.Add(connInfo); err != nil {
|
||||
s.Logger.Error(s.ctx, fmt.Sprintf("Failed to store connection to SQLite: %v", err))
|
||||
// 不影响连接建立,仅记录错误
|
||||
}
|
||||
|
||||
// 启动消息接收协程
|
||||
go s.receiveMessages(tcpConn)
|
||||
}
|
||||
@@ -121,6 +152,11 @@ func (s *TCPServer) receiveMessages(conn *TcpConnection) {
|
||||
}
|
||||
s.Connection.Remove(conn.Id)
|
||||
conn.Server.Close()
|
||||
// 从SQLite移除
|
||||
if err := s.Connection.sqlitePool.Remove(conn.Id); err != nil {
|
||||
s.Logger.Error(s.ctx, fmt.Sprintf("Failed to remove connection from SQLite: %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()
|
||||
|
||||
// 更新SQLite中的连接信息
|
||||
connInfo, err := s.Connection.sqlitePool.Get(conn.Id)
|
||||
if err == nil && connInfo != nil {
|
||||
connInfo.LastUsed = now
|
||||
if err := s.Connection.sqlitePool.Update(connInfo); err != nil {
|
||||
s.Logger.Error(s.ctx, fmt.Sprintf("Failed to update connection in SQLite: %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
|
||||
|
||||
// 更新SQLite中的连接信息
|
||||
connInfo, err := s.Connection.sqlitePool.Get(conn.Id)
|
||||
if err == nil && connInfo != nil {
|
||||
connInfo.LastUsed = now
|
||||
if err := s.Connection.sqlitePool.Update(connInfo); err != nil {
|
||||
s.Logger.Error(s.ctx, fmt.Sprintf("Failed to update connection in SQLite: %v", err))
|
||||
// 不影响消息发送,仅记录错误
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -224,11 +283,21 @@ func (s *TCPServer) Kick(connID string) error {
|
||||
conn.Server.Close()
|
||||
// 从连接池移除
|
||||
s.Connection.Remove(connID)
|
||||
// 从SQLite移除
|
||||
if err := s.Connection.sqlitePool.Remove(connID); err != nil {
|
||||
s.Logger.Error(s.ctx, fmt.Sprintf("Failed to remove connection from SQLite: %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.sqlitePool.GetAllConnIDs()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user