Posted by: cmani2010 | April 22, 2009

Connecting to a MySQL Master/Slave replication with JDBC and Glassfish

MySQL has been having a lot of traction with customers, partners and developers in India. A very popular architecture for using MySQL for large scale deployments is the MySQL Master/Slave replication (Replication enables data from one MySQL database server (called the master) to be replicated to one or more MySQL database servers (slaves)).
<img src="http://dev.mysql.com/doc/refman/5.0/en/images/scaleout.png" Credit: Image is linked from http://dev.mysql.com/doc/refman/5.0/en/replication-solutions-scaleout.html.

One of things that change for developers, who are used to developing with other databases like Oracle, MS SQL server is the question on connecting to a MySQL master/Slave setup. There are several good resources which explain how to do this:
1. From MySQL web site: A snippet of the code from that article is reproduced below :

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Properties;
import com.mysql.jdbc.ReplicationDriver;
public class ReplicationDriverDemo {
public static void main(String[] args) throws Exception {
ReplicationDriver driver = new ReplicationDriver();
Properties props = new Properties();
// We want this for failover on the slaves
props.put("autoReconnect", "true");
// We want to load balance between the slaves
props.put("roundRobinLoadBalance", "true");
props.put("user", "foo");
props.put("password", "bar");
//
// Looks like a normal MySQL JDBC url, with a
// comma-separated list of hosts, the first
// being the 'master', the rest being any number
// of slaves that the driver will load balance against
//
Connection conn =
driver.connect("jdbc:mysql://master,slave1,slave2,slave3/test",
props);
//
// Perform read/write work on the master
// by setting the read-only flag to "false"
//
conn.setReadOnly(false);
conn.setAutoCommit(false);
conn.createStatement().executeUpdate("UPDATE some_table ....");
conn.commit();
//
// Now, do a query from a slave, the driver automatically picks one
// from the list
//
conn.setReadOnly(true);
ResultSet rs =
conn.createStatement().executeQuery("SELECT a,b FROM alt_table");
.......
}
}

Note: Please refer to the mySQL web site for any updates.

2. If you are using Spring, Hibernate and other popular frameworks, an article at http://neilhan.blogspot.com/2006/11/spring-hibernate-and-mysql-replication.html tells you how to do it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: