Java connects the mysql database with master-slave architecture to achieve automatic failover

Java connects the mysql database with master-slave architecture to achieve automatic failover

Purpose

In the system architecture, generally for high availability, the disaster recovery mechanism will be considered when designing the database architecture. After the main database goes down, it can be switched to the standby database; the switching method is generally divided into manual switching and automatic switching; manual switching, as the name implies, is a human operation. Change the database connection address and restart the service; automatic switching means that the system user automatically switches to a usable database without the user noticing; most automatic switching solutions on the Internet are to add middleware or use keepalive to switch, but if it is a java program If you use jdbc to connect, the mysql driver package (mysql-connector-java-xxx.jar) already has the function of automatically switching failed databases.

Usage

Suppose we have two mysql databases, one primary and one secondary. The primary database IP port is: 192.168.0.1:3306, and the secondary database IP port is: 192.168.0.2:3306. We only need to modify the url data in the jdbc connection; for example,
jdbc:mysql://192.168.0.1:3306,192.168.0.2:3306/mydb?allowMultiQueries=true
in When the 192.168.0.1 database is down, the program will automatically connect to the 192.168.0.2 database without any other configuration.

Official website reference address

https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-config-failover.html

Insert image description here

Guess you like

Origin blog.csdn.net/xuziwen127/article/details/129533129