我们知道,使用mysql驱动Connector/J
的ReplicationDriver
可以实现读写分离,在方法上加入注解@Transactional
(默认是readOnly=false
)是在主库中进行读写的,而使用注解@Transactional(readOnly = true)
则是在从库中进行读的
在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: ******
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).