>데이터 베이스 >MySQL 튜토리얼 >MySQL-JDBC 마스터 슬레이브 구현 샘플 코드

MySQL-JDBC 마스터 슬레이브 구현 샘플 코드

黄舟
黄舟원래의
2017-03-14 14:47:461289검색

오늘은 JDBC에서 Master Slave를 구현하는 코드를 가져오겠습니다. 자, 자세한 설명은 생략하고 바로 코드로 들어가겠습니다.

구체적인 코드는 다음과 같습니다.

package com.lyz.test;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * Mysql JDBC 实现Master Slave
 * 
 * @author liuyazhuang
 * @datetime 2016-11-17
 * 
 */
public class ReplicationDriverTest {
	private static final String URL = "jdbc:mysql://127.0.0.1:3306/test1?useUnicode=true&characterEncoding=utf8";
	private static final String DRIVER = "com.mysql.jdbc.Driver";
	/* Master Slave */
	private static final String replicationURL = "jdbc:mysql:replication://localhost:3306,10.2.15.123:3306/test?useUnicode=true&characterEncoding=utf8";
	/* 负载平衡 */
	private static final String loadBalanceURL = "jdbc:mysql:loadbalance://localhost:3306,10.2.15.123:3306/test?useUnicode=true&characterEncoding=utf8";
	private static final String REPLICATION_DRIVER = "com.mysql.jdbc.ReplicationDriver";

	public static void main(String[] args) throws SQLException {
		// oneDB();
		// replicationDB(URL);
		// replicationDB(replicationURL);
		replicationDB(loadBalanceURL);

	}

	public static void replicationDB(String url) throws SQLException {
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		try {
			dataSource.setDriverClass(REPLICATION_DRIVER);
		} catch (PropertyVetoException e1) {
			e1.printStackTrace();
		}
		dataSource.setJdbcUrl(url);
		dataSource.setMaxPoolSize(10);
		dataSource.setMinPoolSize(10);
		dataSource.setUser("kevin");
		dataSource.setPassword("123456");
		dataSource.setCheckoutTimeout(1000);
		dataSource.setDataSourceName("datasource");
		dataSource.setInitialPoolSize(10);
		try {
			Connection connection = dataSource.getConnection();
			connection.setReadOnly(true);//设置为只读,代理类将会获取Slave数据库连接,否则设置Master连接
			java.sql.PreparedStatement pStatement_ = connection.prepareStatement("SELECT user_id, username, PASSWORD, email  FROM account_0 LIMIT 0,3;");
			ResultSet rs = pStatement_.executeQuery();
			while (rs.next()) {
				System.out.println(rs.getInt(1) + "\t" + rs.getString(2) + "\t" + rs.getString(3) + "\t" + rs.getString(4));
			}
			rs.close();
			pStatement_.close();
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		Connection connection = dataSource.getConnection();
		connection.setReadOnly(false);//设置为只读,代理类将会获取Slave数据库连接,否则设置Master连接
		java.sql.PreparedStatement pStatement_ = connection.prepareStatement("UPDATE account_0 SET  username = 'kevin' ,PASSWORD = 'password' ,email = 'xxxx' WHERE user_id = '1001' ;");
		int row = pStatement_.executeUpdate();
		System.out.println(row);
		pStatement_.close();
		connection.close();
	}

	public static void oneDB() throws SQLException {
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		try {
			dataSource.setDriverClass(DRIVER);
		} catch (PropertyVetoException e1) {
			e1.printStackTrace();
		}
		dataSource.setJdbcUrl(URL);
		dataSource.setMaxPoolSize(10);
		dataSource.setMinPoolSize(10);
		dataSource.setUser("root");
		dataSource.setPassword("123456");
		dataSource.setCheckoutTimeout(1000);
		dataSource.setDataSourceName("datasource00");
		dataSource.setInitialPoolSize(10);
		try {
			Connection connection = dataSource.getConnection();
			java.sql.PreparedStatement pStatement_ = connection.prepareStatement("SELECT * FROM user limit 1");
			ResultSet rs = pStatement_.executeQuery();
			while (rs.next()) {
				System.out.println(rs.getInt(1) + "\t" + rs.getString(2) + "\t" + rs.getString(3) + "\t" + rs.getString(4));
			}
			rs.close();
			pStatement_.close();
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		Connection connection = dataSource.getConnection();
		java.sql.PreparedStatement pStatement_ = connection.prepareStatement("UPDATE user SET	NAME = 'KEVIN-LUAN' , sex = '1' , age = '89' WHERE id = 16 ;");
		int row = pStatement_.executeUpdate();
		System.out.println(row);
		pStatement_.close();
		connection.close();
	}
}

위 내용은 MySQL-JDBC 마스터 슬레이브 구현 샘플 코드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.