xugu_connector.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package xugu
  2. import (
  3. "context"
  4. "database/sql/driver"
  5. "fmt"
  6. "net"
  7. "time"
  8. )
  9. type connector struct {
  10. dsn string
  11. }
  12. // Driver implements driver.Connector interface.
  13. // Driver returns &XuguDriver{}
  14. func (conntor *connector) Driver() driver.Driver {
  15. fmt.Println(">>>>>(conntor *connector) Driver()")
  16. return &XuguDriver{}
  17. }
  18. // Connect implements driver.Connector interface.
  19. // Connect returns a connection to the database.
  20. /*
  21. dsn解析
  22. 创建连接
  23. 设置为 tcp 长连接(
  24. 创建连接缓冲区
  25. 设置连接超时配置
  26. 接收来自服务端的握手请求
  27. */
  28. func (conntor *connector) Connect(ctx context.Context) (driver.Conn, error) {
  29. fmt.Println(">>>>>(conntor *connector) Connect(ctx context.Context) ")
  30. dsnConfig := parseDSN(conntor.dsn)
  31. xgConn := &xuguConn{conn: nil}
  32. xgConn.dsnConfig = dsnConfig
  33. nd := net.Dialer{Timeout: 5 * time.Second}
  34. netConn, err := nd.DialContext(ctx, "tcp", fmt.Sprintf("%s:%s", xgConn.IP, xgConn.Port))
  35. if err != nil {
  36. fmt.Println("tcp error", err)
  37. return nil, err
  38. }
  39. // 启用 TCP 保活
  40. if tc, ok := netConn.(*net.TCPConn); ok {
  41. if err := tc.SetKeepAlive(true); err != nil {
  42. //c.cfg.Logger.Print(err) // 如果设置保活失败,记录错误但不终止
  43. fmt.Println("SetKeepAlive error", err)
  44. }
  45. }
  46. xgConn.conn = netConn
  47. xgConn.Type = HT_CONN
  48. xgConn.readBuff = newBuffer(xgConn.conn)
  49. fmt.Println("连接串为: ", conntor.dsn)
  50. err = xgSockOpenConn(ctx, xgConn)
  51. if err != nil {
  52. return nil, err
  53. }
  54. return xgConn, nil
  55. }