【源码阅读】Golang中的go-sql-driver库源码探究

devtools/2024/10/18 19:22:08/

文章目录

    • 前言
    • 一、go-sql-driver/mysql
      • 1、驱动注册:sql.Register
      • 2、驱动实现:MysqlDriver
      • 3、RegisterDialContext
    • 二、总结

前言

在上篇文章中我们知道,database/sql只是提供了驱动相关的接口,并没有相关的具体实现,具体内容是由第三方实现的,如go-sql-driver/mysql:https://github.com/go-sql-driver/mysql/,本章中我们主要是探究这个驱动实现库的具体实现。以及它是如何与database/sql一起作用的。

sqldrivermysql_4">一、go-sql-driver/mysql

go-sql-driver作为一个三方驱动库,主要就是实现database/sql中的驱动接口了,因此,主要的文件也就是driver.go、connector.go和connection.go几个文件了。因此,本章的阅读业主要聚焦与这三个文件中的源码内容。
在这里插入图片描述

sqlRegister_7">1、驱动注册:sql.Register

通常,我们都会这样调用database/sql的Open方法创建一个db实例:

import ("database/sql"_ "github.com/go-sql-driver/mysql"
)// ...db, err := sql.Open("mysql", "user:password@/dbname")
if err != nil {panic(err)
}

初看是不是觉得很奇怪,在这段代码中,我们没有直接使用到go-sql-driver的的任何东西,但却需要引入这个包,这是因为,sql.Open方法中,我们知道,会检查获取对应的驱动,而驱动的注册是由第三方驱动实现包调用Register方法完成的。

在go-sql-driver中的driver.go中,我们发现init函数中会调用Register方法注册相应的驱动,这也是上面的代码中为什么需要引入这个包的原因。

func init() {if driverName != "" {sql.Register(driverName, &MySQLDriver{})}
}

sqlDriver_34">2、驱动实现:MysqlDriver

在go-sql-driver中,核心的driver.go中实现了具体的mysql驱动(MysqlDriver)

// Open new Connection.
// See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how
// the DSN string is formatted
func (d MySQLDriver) Open(dsn string) (driver.Conn, error) {cfg, err := ParseDSN(dsn)if err != nil {return nil, err}c := newConnector(cfg)return c.Connect(context.Background())
}

在该方法中,首先从数据源dsn中解析出对应的配置,然后再构造对应的连接器,调用连接器的Connect方法与mysql建立连接。

connector实现了driver.Connector接口,其中Connect方法主要是与mysql进行交互,包括:拨号(dial)、认证、利用mysql协议发包与收包处理结果等,

type connector struct {cfg               *Config // immutable private copy.encodedAttributes string  // Encoded connection attributes.
}func newConnector(cfg *Config) *connector {encodedAttributes := encodeConnectionAttributes(cfg)return &connector{cfg:               cfg,encodedAttributes: encodedAttributes,}
}// Connect implements driver.Connector interface.
// Connect returns a connection to the database.
func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {var err error// Invoke beforeConnect if present, with a copy of the configurationcfg := c.cfgif c.cfg.beforeConnect != nil {cfg = c.cfg.Clone()err = c.cfg.beforeConnect(ctx, cfg)if err != nil {return nil, err}}// New mysqlConnmc := &mysqlConn{maxAllowedPacket: maxPacketSize,maxWriteSize:     maxPacketSize - 1,closech:          make(chan struct{}),cfg:              cfg,connector:        c,}mc.parseTime = mc.cfg.ParseTime// Connect to ServerdialsLock.RLock()dial, ok := dials[mc.cfg.Net]dialsLock.RUnlock()if ok {dctx := ctxif mc.cfg.Timeout > 0 {var cancel context.CancelFuncdctx, cancel = context.WithTimeout(ctx, c.cfg.Timeout)defer cancel()}mc.netConn, err = dial(dctx, mc.cfg.Addr)} else {nd := net.Dialer{Timeout: mc.cfg.Timeout}mc.netConn, err = nd.DialContext(ctx, mc.cfg.Net, mc.cfg.Addr)}if err != nil {return nil, err}mc.rawConn = mc.netConn// Enable TCP Keepalives on TCP connectionsif tc, ok := mc.netConn.(*net.TCPConn); ok {if err := tc.SetKeepAlive(true); err != nil {c.cfg.Logger.Print(err)}}// Call startWatcher for context support (From Go 1.8)mc.startWatcher()if err := mc.watchCancel(ctx); err != nil {mc.cleanup()return nil, err}defer mc.finish()mc.buf = newBuffer(mc.netConn)// Set I/O timeoutsmc.buf.timeout = mc.cfg.ReadTimeoutmc.writeTimeout = mc.cfg.WriteTimeout// Reading Handshake Initialization PacketauthData, plugin, err := mc.readHandshakePacket()if err != nil {mc.cleanup()return nil, err}if plugin == "" {plugin = defaultAuthPlugin}// Send Client Authentication PacketauthResp, err := mc.auth(authData, plugin)if err != nil {// try the default auth plugin, if using the requested plugin failedc.cfg.Logger.Print("could not use requested auth plugin '"+plugin+"': ", err.Error())plugin = defaultAuthPluginauthResp, err = mc.auth(authData, plugin)if err != nil {mc.cleanup()return nil, err}}if err = mc.writeHandshakeResponsePacket(authResp, plugin); err != nil {mc.cleanup()return nil, err}// Handle response to auth packet, switch methods if possibleif err = mc.handleAuthResult(authData, plugin); err != nil {// Authentication failed and MySQL has already closed the connection// (https://dev.mysql.com/doc/internals/en/authentication-fails.html).// Do not send COM_QUIT, just cleanup and return the error.mc.cleanup()return nil, err}if mc.cfg.MaxAllowedPacket > 0 {mc.maxAllowedPacket = mc.cfg.MaxAllowedPacket} else {// Get max allowed packet sizemaxap, err := mc.getSystemVar("max_allowed_packet")if err != nil {mc.Close()return nil, err}mc.maxAllowedPacket = stringToInt(maxap) - 1}if mc.maxAllowedPacket < maxPacketSize {mc.maxWriteSize = mc.maxAllowedPacket}// Handle DSN Paramserr = mc.handleParams()if err != nil {mc.Close()return nil, err}return mc, nil
}// Driver implements driver.Connector interface.
// Driver returns &MySQLDriver{}.
func (c *connector) Driver() driver.Driver {return &MySQLDriver{}
}

同时,我们还注意到,Connect方法中调用了一个startWatcher方法,该方法从watcher通道中接收一个ctx,并对这个ctx进行监听,每次都会调用一个watchCancel方法将ctx传递Watcher,watcher监听到ctx.Done的信号后,将会调用cancel方法,启动清理工作。

func (mc *mysqlConn) startWatcher() {watcher := make(chan context.Context, 1)mc.watcher = watcherfinished := make(chan struct{})mc.finished = finishedgo func() {for {var ctx context.Contextselect {case ctx = <-watcher:case <-mc.closech:return}select {case <-ctx.Done():mc.cancel(ctx.Err())case <-finished:case <-mc.closech:return}}}()
}

cancel方法将会调用cleanup方法进行连接的清理工作,可以看到在cleanup中调用了conn.Close,将这个物理连接关闭掉。因此,我们在使用QueryContext或者ExecContext时候,如果ctx设置了超时时间,或者主动cancel,那么意味着这个连接将会被断掉。极端情况下,大量连接同时超时,意味着连接都将失效,此时再有新的请求打进来则会重新建立新的连接,会有一定的连接建立开销。由于连接池是database/sql维护的,因此这也只是客户端(或者说mysql sdk)层面的失效,mysql server接收到的sql执行是不会被中断的。

// finish is called when the query has canceled.
func (mc *mysqlConn) cancel(err error) {mc.canceled.Set(err)mc.cleanup()
}// Closes the network connection and unsets internal variables. Do not call this
// function after successfully authentication, call Close instead. This function
// is called before auth or on auth failure because MySQL will have already
// closed the network connection.
func (mc *mysqlConn) cleanup() {if mc.closed.Swap(true) {return}// Makes cleanup idempotentclose(mc.closech)conn := mc.rawConnif conn == nil {return}if err := conn.Close(); err != nil {mc.log(err)}// This function can be called from multiple goroutines.// So we can not mc.clearResult() here.// Caller should do it if they are in safe goroutine.
}

在实际项目中,为了减少使用层面的超时导致连接失效这种情况,我们也可以对mysql server设置一个wait_timeout时间,并且调用QueryContext/ExecContext的超时时间要小于这个wait_timeout时间,这样则不会由于某业务中有慢查的sql,导致ctx超时,从而频繁触发连接的重新建立。

3、RegisterDialContext

最后我们再看看下这个静态方法:RegisterDialContext,这个方法主要作用就是注册对应的协议的dialFunc,便于在进行数据库连接时候找到真正的地址。

// RegisterDialContext registers a custom dial function. It can then be used by the
// network address mynet(addr), where mynet is the registered new network.
// The current context for the connection and its address is passed to the dial function.
func RegisterDialContext(net string, dial DialContextFunc) {dialsLock.Lock()defer dialsLock.Unlock()if dials == nil {dials = make(map[string]DialContextFunc)}dials[net] = dial
}// DialContextFunc is a function which can be used to establish the network connection.
// Custom dial functions must be registered with RegisterDialContext
type DialContextFunc func(ctx context.Context, addr string) (net.Conn, error)

二、总结

本篇文章我们看了go-sql-driver的具体实现,整体上来说,go-sql-driver都是实现database/sql的driver.Driver接口,直接对接mysql服务端,支持mysql协议的收发包,在api层面,query/exec两个方法都提供了带ctx的方法,带ctx和不带ctx的api使用差异,一点小小的切换可能导致不断频繁建立连接与关闭连接等,最后我们也根据实际的情况提出解决此问题的方案。


http://www.ppmy.cn/devtools/28374.html

相关文章

<一起学管理>《微课堂2:什么是MSA? 》

1 MSA是什么 测量系统分析(Measurement Systems Analysis&#xff0c;MSA) 的定义&#xff1a;通过统计分析的手段&#xff0c;对构成测量系统的各个影响因子进行统计变差分析和研究以得到测量系统是否准确可靠的结论。 MSA是一种质量管理的工具。 测量系统可分为“计数型”…

【笔试题汇总】华为春招笔试题题解 2024-3-20

这里是paoxiaomo&#xff0c;一个现役ACMer&#xff0c;之后将会持续更新算法笔记系列以及笔试题题解系列 本文章面向想打ICPC/蓝桥杯/天梯赛等程序设计竞赛&#xff0c;以及各个大厂笔试的选手 感谢大家的订阅➕ 和 喜欢&#x1f497; 有什么想看的算法专题可以私信博主 &…

浅析扩散模型与图像生成【应用篇】(十七)——LDM

17. High-Resolution Image Synthesis with Latent Diffusion Models 该文首次提出在潜在特征空间中的扩散模型LDM&#xff0c;也是大名鼎鼎的Stable Diffusion&#xff08;SD&#xff09;模型的基础。不同于之前的扩散模型直接在图像维度上进行扩散和去噪&#xff0c;LDM首先训…

【Python】常用数据结构

1、熟悉字典和列表 2、使用条件判断语句 3、list列表中计算 1、从键盘输人一个正整数列表,以-1结束,分别计算列表中奇数和偶数的和。 &#xff08;1&#xff09;源代码&#xff1a; # 初始化奇数和偶数的和为0 odd_sum 0 even_sum 0 #输入 while True:num int(input(&qu…

如何将安卓手机投屏到Windows 10电脑上

诸神缄默不语-个人CSDN博文目录 我之所以要干这个事是为了用手机直播的时候在电脑上看弹幕…… 文章目录 1. 方法一&#xff1a;直接用Win10内置的投影到此电脑2. 方法二&#xff1a;用AirDroid Cast投屏到电脑上 1. 方法一&#xff1a;直接用Win10内置的投影到此电脑 在设置…

【docker】docker compose 搭建私服

安装 Docker Registry 创建目录 mkdir -pv /usr/local/docker/registrymkdir -pv /usr/local/docker/data 创建 docker-compose.yml文件 进入目录创建docker-compose.yml cd /usr/local/docker/registrytouch docker-compose.yml 编辑docker-compose.yml vim docker-compo…

探索密码学的奥秘:保护信息安全的基石与挑战

目录 概述 1.密码学的概念 2.典型对称密码系统 1.数据加密标准&#xff08;DES&#xff09; 高级加密标准&#xff08;AES&#xff09; 3.典型公开密码系统 1.RSA算法 2..椭圆曲线密码学&#xff08;ECC&#xff09; 4.国密算法 1.SM2 2. SM3 3. SM4 5.密码分析 …

详解SDRAM基本原理以及FPGA实现读写控制

文章目录 一、SDRAM简介二、SDRAM存取结构以及原理2.1 BANK以及存储单元结构2.2 功能框图2.3 SDRAM速度等级以及容量计算 三、SDRAM操作命令3.1 禁止命令&#xff1a; 4b1xxx3.2 空操作命令&#xff1a;4b01113.3 激活命令&#xff1a;4b00113.4 读命令&#xff1a;4b01013.5 写…