Mysql Connector/J 源码分析(Failover)

文章目录


前言

本文讨论Connector/J 的failover模块。本文将以两个区分(区分构造阶段和使用阶段;区分通讯异常和数据异常)来分析failover的使用价值。

本次分析的版本为5.1.46。若通过maven下载,可添加以下依赖:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.46</version>
</dependency>

 我们获取连接的例子如下:

    Connection conn = null;
    URL =“jdbc:mysql://ip1:port1,ip2:port2,ip3:port3/dbname”;
    try{
        // 注册 JDBC 驱动
        Class.forName("com.mysql.jdbc.Driver");

        // 打开链接
        conn = DriverManager.getConnection(DB_URL,USER,PASS);
    ....

 


一、什么是Failover?

官方用两段文字对Failover进行描述:

MySQL Connector/J supports server failover. A failover happens when connection-related errors occur for an underlying, active connection. The connection errors are, by default, propagated to the client, which has to handle them by, for example, recreating the working objects (Statement, ResultSet, etc.) and restarting the processes. Sometimes, the driver might eventually fall back to the original host automatically before the client application continues to run, in which case the host switch is transparent and the client application will not even notice it.

A connection using failover support works just like a standard connection: the client does not experience any disruptions in the failover process. This means the client can rely on the same connection instance even if two successive statements might be executed on two different physical hosts. However, this does not mean the client does not have to deal with the exception that triggered the server switch.

大意是说,通常情况下连接发生异常,调用方就得放充当前连接,获取新连接,重新一遍之前的操作。而有了failover特性后,它会在底层的连接出状况时候产生作用,它不会让调用方当前的操作崩掉而重新再来。在failover的作用下,调用方只需保持着一个连接,尽管前后两条SQL命令有可能在两台不同的设备上执行。

通过官方的描述,看起来调用方很轻松,拿看一个连接就可走天下了。但细想一下,如果当前的操作是带事务的,前后两条命令在不同设备上执行,事务还会生效?官方的最后一句是说有了failover并不意味着的调用方可以高枕无忧,那么到底调用方在什么情况下需要做什么处理呢?后续章节将一一解疑。


二、Failover的主要结构

 

我们以UML类图展示其内部结构:

主要组件功能如下:

 - MysqlIO:负责与Mysql服务器建立tcp链接。
- ConnectionImpl、JDBC4Connection:通过MysqlIO控制与Mysql服务器间的连接,实现数据操作的接口方法。并设定和记录各种连接时间。
- MultiHostMySQLConnection、JDBC4MultiHostMySQLConnection:它们之间是继承关系。通过代理对象FailoverConnectionProxy获取JDBC4Connection对象,并调用其对应的接口方法(从JDBC4MySQLConnection到java.sql.Connection声明的方法)。
- MultiHostConnectionProxy:作为各种动态类的父类,实现了各种动态类的公共方法,最常见的就是返回当前连接对象给到MultiHostMySQLConnection及其子类。它还是InvocationHandler接口的直接实现类,它重载了invoke方法,并声明了由其子类实现的虚方法invokeMore。invoke方法的实现使用了模板方法这种设计模式。通过invoke方法和子类的invokeMore方法,一起实现了代理模式,即在被代理方法执行之前和之后都添加了一些行为。
- FailoverConnectionProxy作为MultiHostConnectionProxy的子类重载了invokeMore方法。当发生异常时,在被代理方法执行前或者后,通过failover方法更换当前连接对象。


三、异常处理

从官网的描述可以理解到,failover就是要解决出现

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值