conn.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Author: simon (ynwdlxm@163.com)
  2. // Date: 2025/9/12 11:02
  3. // Desc: Encapsulation of each connection (description of each client connection)
  4. package connection
  5. import (
  6. "net"
  7. "sync"
  8. "time"
  9. "github.com/runningwater/go-redis/lib/logger"
  10. "github.com/runningwater/go-redis/lib/sync/wait"
  11. )
  12. // Connection represents a client connection to the Redis server
  13. type Connection struct {
  14. conn net.Conn
  15. waiting wait.Wait
  16. mu sync.Mutex
  17. selectedDB int
  18. }
  19. // NewConnection creates a new connection wrapper
  20. func NewConnection(conn net.Conn) *Connection {
  21. return &Connection{
  22. conn: conn,
  23. }
  24. }
  25. // RemoteAddr returns the remote network address
  26. func (c *Connection) RemoteAddr() net.Addr {
  27. return c.conn.RemoteAddr()
  28. }
  29. // Close closes the connection
  30. func (c *Connection) Close() error {
  31. timeout := c.waiting.WaitWithTimeout(10 * time.Second)
  32. if timeout {
  33. logger.Info("timeout to close connection")
  34. } else {
  35. logger.Info("connection closed")
  36. }
  37. err := c.conn.Close()
  38. return err
  39. }
  40. // Write writes data to the connection
  41. func (c *Connection) Write(bytes []byte) error {
  42. if len(bytes) == 0 {
  43. return nil
  44. }
  45. logger.InfoC("write to client: ", string(bytes))
  46. c.mu.Lock()
  47. c.waiting.Add(1)
  48. defer func() {
  49. c.waiting.Done()
  50. c.mu.Unlock()
  51. }()
  52. _, err := c.conn.Write(bytes)
  53. return err
  54. }
  55. // GetDBIndex returns the currently selected database index
  56. func (c *Connection) GetDBIndex() int {
  57. return c.selectedDB
  58. }
  59. // SelectDB selects a database
  60. func (c *Connection) SelectDB(dbNum int) {
  61. c.selectedDB = dbNum
  62. }