使用mysql-connector-java(Connector/J)驱动实现读写分离

曹旭东
2023-12-01

使用mysql-connector-java(Connector/J)驱动实现读写分离

序言

我们知道,使用mysql驱动Connector/JReplicationDriver可以实现读写分离,在方法上加入注解@Transactional(默认是readOnly=false)是在主库中进行读写的,而使用注解@Transactional(readOnly = true)则是在从库中进行读的

Connector/J 5.1.38以前配置

mysql-connector-java(Connector/J 5.1.38)以前,我们是这样配置读写分离:

spring:
  datasource:
    url: jdbc:mysql:replication://master:port,slave:port/db?characterEncoding=utf8
    driver-class-name: com.mysql.jdbc.ReplicationDriver
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: ******
    password: ******

Connector/J 5.1.38以后配置

spring:
  datasource:
    url: jdbc:mysql:replication://master:port,slave:port/db?characterEncoding=utf8
    &useSSL=false&autoReconnect=true&allowMasterDownConnections=true
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: ******
    password: ******

Connector/J 5.1.38之后,开始使用com.mysql.cj.jdbc.Driver这个驱动了,在Connector/J 6.*之后,好像就舍弃了com.mysql.jdbc.ReplicationDriver。在使用com.mysql.cj.jdbc.Driver驱动的时候,需要在ulr后加入allowMasterDownConnections=true

官网是这么说的:

For Connector/J 5.1.38 and later, users may specify the property allowSlavesDownConnections=true to allow Connection objects to be created even though no slave hosts are reachable. A Connection then, at runtime, tests for available slave hosts when Connection.setReadOnly(true) is called (see explanation for the method below), throwing an SQLException if it cannot establish a connection to a slave, unless the property readFromMasterWhenNoSlaves is set to be “true” (see below for a description of the property).

 类似资料: