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

本文介绍如何使用mysql-connector-java(Connector/J)驱动实现数据库读写分离。详细讲解了5.1.38版本前后的配置变化,并指出新版本中需要加入特定参数以确保连接可用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值