pg.ddx.io pgsql-jdbc@postgresql.org mailing list archive
help / color / mirror / Atom feed From: Chen Huajun <chenhj@cn.fujitsu.com>
To: List <pgsql-jdbc@postgresql.org>
Subject: Re: performance problem of Failover Datasource?
Date: Mon, 24 Dec 2012 18:26:29 +0800
Message-ID: <50D82DD5.5020903@cn.fujitsu.com> (raw )
In-Reply-To: <50CFB362.4080701@cn.fujitsu.com >
References: <4DFA5A86.9030301@acm.org >
<itdn5g$eu7$1@dough.gmane.org >
<4DFA671F.2050005@acm.org >
<4DFA9704.4000209@hogranch.com >
<4DFAB403.5010309@acm.org >
<4DFAB5B8.5010603@hogranch.com >
<4DFAB9E2.4070905@acm.org >
<1334056170219-5629626.post@n5.nabble.com >
<1355303340886-5736270.post@n5.nabble.com >
<50C9B102.2060208@cn.fujitsu.com >
<CADK3HH+TLPjrrJ=cQWqZ+0B5o96xR+sTVcvqhcDU4CjyryKG2g@mail.gmail.com >
<50CA959E.4060603@cn.fujitsu.com >
<50CB29BD.6090903@cn.fujitsu.com >
<50CC2279.3090301@cn.fujitsu.com >
<alpine.WNT.2.00.1212151055200.6544@turks >
<50CFB362.4080701@cn.fujitsu.com >
List-Unsubscribe: <mailto:majordomo@postgresql.org?body=unsub%20pgsql-jdbc>
Hi
I have made a new patch(with my test). Please give a look.
It support the following features
1) performance improve for fail over by avoiding dead hosts.
2) simple load balance by picking up the first host from multiple valid hosts randomly.
3) ability of choosing master or slave to connect to.
And in the patch, three connection parameters were added.
targetServerType = String
Specifies what kind of server to connect.The value should be one of the following:
any
master
slave
slavefirst (Try connecting to the slaves first.If failed try the master)
The default is 'any'.
enableLoadBalance = boolean
Enable or disable load balance when multiple hosts were specified;If load balance is enabled,specified multiple hosts will be picked up randomly.
The default is false.
failedHostCheckPeriod = int
Specifies period(seconds) to check whether the failed hosts had been repaired, when load balance is enabled; 0 means never check.
The default is 600 seconds.
(2012/12/18 8:05), Chen Huajun wrote:
>
> Thanks for you advise.
> I will try to made a new patch and add load balance supporting.
>
>
--
Best Regards,
Chen Huajun
--
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc
Attachments:
pgjdbc_failover_loadbalance_for_mutihosts.patch (text/plain, 28.6K) download
diff --git a/build.xml b/build.xml
index c9c5660..e34f85f 100644
--- a/build.xml
+++ b/build.xml
@@ -132,6 +132,7 @@
<include name="${package}/fastpath/**" />
<include name="${package}/geometric/**" />
<include name="${package}/largeobject/**" />
+ <include name="${package}/hostchooser/**" />
<include name="${package}/util/**" />
<!--
diff --git a/org/postgresql/Driver.java.in b/org/postgresql/Driver.java.in
index f6c69c0..3f9eacc 100644
--- a/org/postgresql/Driver.java.in
+++ b/org/postgresql/Driver.java.in
@@ -465,7 +465,14 @@
{ "kerberosServerName", Boolean.FALSE,
"The Kerberos service name to use when authenticating with GSSAPI. This is equivalent to libpq's PGKRBSRVNAME environment variable." },
{ "jaasApplicationName", Boolean.FALSE,
- "Specifies the name of the JAAS system or application login configuration." }
+ "Specifies the name of the JAAS system or application login configuration." },
+ { "targetServerType", Boolean.FALSE,
+ "Specifies what kind of server to connect.",
+ new String[] { "any", "master", "slave", "slavefirst" } },
+ { "enableLoadBalance", Boolean.FALSE,
+ "Enable or disable load balance when multiple hosts were specified;If load balance is enabled,specified multiple hosts will be picked up randomly."},
+ { "failedHostCheckPeriod", Boolean.FALSE,
+ "Specifies period(seconds) to check whether the failed hosts had been repaired, when load balance is enabled; 0 means never check." }
};
/**
diff --git a/org/postgresql/core/v2/ConnectionFactoryImpl.java b/org/postgresql/core/v2/ConnectionFactoryImpl.java
index a0cfc96..7935cc4 100644
--- a/org/postgresql/core/v2/ConnectionFactoryImpl.java
+++ b/org/postgresql/core/v2/ConnectionFactoryImpl.java
@@ -8,6 +8,7 @@
*/
package org.postgresql.core.v2;
+import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
@@ -17,6 +18,9 @@
import java.net.ConnectException;
import org.postgresql.core.*;
+import org.postgresql.hostchooser.HostChooser;
+import org.postgresql.hostchooser.HostChooserFactory;
+import org.postgresql.hostchooser.HostStatus;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.UnixCrypt;
@@ -69,9 +73,20 @@
// - the TCP keep alive setting
boolean requireTCPKeepAlive = (Boolean.valueOf(info.getProperty("tcpKeepAlive")).booleanValue());
+
+ // - the targetServerType setting
+ String targetServerType = info.getProperty("targetServerType","any").toLowerCase();
+ if (!"any".equals(targetServerType) &&
+ !"master".equals(targetServerType) &&
+ !"slave".equals(targetServerType) &&
+ !"slavefirst".equals(targetServerType)){
+ throw new PSQLException (GT.tr("Invalid targetServerType value: {0}", targetServerType), PSQLState.CONNECTION_UNABLE_TO_CONNECT);
+ }
- for (int whichHost = 0; whichHost < hostSpecs.length; ++whichHost) {
- HostSpec hostSpec = hostSpecs[whichHost];
+ HostChooser hostChooser = HostChooserFactory.createHostChooser(hostSpecs, info);
+ Iterator<HostSpec> hostIter = hostChooser.iterator();
+ while(hostIter.hasNext()) {
+ HostSpec hostSpec = hostIter.next();
if (logger.logDebug())
logger.debug("Trying to establish a protocol version 2 connection to " + hostSpec);
@@ -115,6 +130,41 @@
ProtocolConnectionImpl protoConnection = new ProtocolConnectionImpl(newStream, user, database, logger);
readStartupMessages(newStream, protoConnection, logger);
+ // Check Master or Slaver
+ if(targetServerType.equals("any")){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectOK);
+ }else if(targetServerType.equals("master")){
+ if(isMaster(protoConnection, logger)){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Master);
+ }else{
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Slave);
+ protoConnection.close();
+ if (hostIter.hasNext()) {
+ // still more addresses to try
+ continue;
+ }
+ throw new PSQLException (GT.tr("Couldn't find a server with specified targetServerType: {0}", targetServerType) , PSQLState.CONNECTION_UNABLE_TO_CONNECT);
+ }
+ }else if(targetServerType.equals("slave")){
+ if(isMaster(protoConnection, logger)){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Master);
+ protoConnection.close();
+ if (hostIter.hasNext()) {
+ // still more addresses to try
+ continue;
+ }
+ throw new PSQLException (GT.tr("Couldn't find a server with specified targetServerType: {0}", targetServerType) , PSQLState.CONNECTION_UNABLE_TO_CONNECT);
+ }else{
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Slave);
+ }
+ }else{//slaveFirst
+ if(isMaster(protoConnection, logger)){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Master);
+ }else{
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Slave);
+ }
+ }
+
// Run some initial queries
runInitialQueries(protoConnection, info, logger);
@@ -127,7 +177,8 @@
// ConnectException is thrown when the connection cannot be made.
// we trap this an return a more meaningful message for the end user
- if (whichHost + 1 < hostSpecs.length) {
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectFail);
+ if (hostIter.hasNext()) {
// still more addresses to try
continue;
}
@@ -146,7 +197,8 @@
}
}
- if (whichHost + 1 < hostSpecs.length) {
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectFail);
+ if (hostIter.hasNext()) {
// still more addresses to try
continue;
}
@@ -165,7 +217,8 @@
}
}
- if (whichHost + 1 < hostSpecs.length) {
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectFail);
+ if (hostIter.hasNext()) {
// still more addresses to try
continue;
}
@@ -401,7 +454,7 @@
}
}
}
-
+
private void runInitialQueries(ProtocolConnectionImpl protoConnection, Properties info, Logger logger) throws SQLException, IOException {
byte[][] results = SetupQueryRunner.run(protoConnection, "set datestyle = 'ISO'; select version(), case when pg_encoding_to_char(1) = 'SQL_ASCII' then 'UNKNOWN' else getdatabaseencoding() end", true);
@@ -485,4 +538,11 @@
SetupQueryRunner.run(protoConnection, sb.toString(), false);
}
}
+
+
+ private boolean isMaster(ProtocolConnectionImpl protoConnection, Logger logger)throws SQLException, IOException {
+ byte[][] results = SetupQueryRunner.run(protoConnection, "show transaction_read_only", true);
+ String value = protoConnection.getEncoding().decode(results[0]);
+ return value.equalsIgnoreCase("off");
+ }
}
diff --git a/org/postgresql/core/v3/ConnectionFactoryImpl.java b/org/postgresql/core/v3/ConnectionFactoryImpl.java
index 95eaa43..b4f4b0b 100644
--- a/org/postgresql/core/v3/ConnectionFactoryImpl.java
+++ b/org/postgresql/core/v3/ConnectionFactoryImpl.java
@@ -8,6 +8,7 @@
*/
package org.postgresql.core.v3;
+import java.util.Iterator;
import java.util.Properties;
import java.util.TimeZone;
@@ -16,6 +17,9 @@
import java.net.ConnectException;
import org.postgresql.core.*;
+import org.postgresql.hostchooser.HostChooser;
+import org.postgresql.hostchooser.HostChooserFactory;
+import org.postgresql.hostchooser.HostStatus;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.PSQLWarning;
@@ -78,6 +82,15 @@
// - the TCP keep alive setting
boolean requireTCPKeepAlive = (Boolean.valueOf(info.getProperty("tcpKeepAlive")).booleanValue());
+ // - the targetServerType setting
+ String targetServerType = info.getProperty("targetServerType","any").toLowerCase();
+ if (!"any".equals(targetServerType) &&
+ !"master".equals(targetServerType) &&
+ !"slave".equals(targetServerType) &&
+ !"slavefirst".equals(targetServerType)){
+ throw new PSQLException (GT.tr("Invalid targetServerType value: {0}", targetServerType), PSQLState.CONNECTION_UNABLE_TO_CONNECT);
+ }
+
// NOTE: To simplify this code, it is assumed that if we are
// using the V3 protocol, then the database is at least 7.4. That
// eliminates the need to check database versions and maintain
@@ -85,8 +98,10 @@
//
// Change by Chris Smith <cdsmith@twu.net>
- for (int whichHost = 0; whichHost < hostSpecs.length; ++whichHost) {
- HostSpec hostSpec = hostSpecs[whichHost];
+ HostChooser hostChooser = HostChooserFactory.createHostChooser(hostSpecs, info);
+ Iterator<HostSpec> hostIter = hostChooser.iterator();
+ while(hostIter.hasNext()) {
+ HostSpec hostSpec = hostIter.next();
if (logger.logDebug())
logger.debug("Trying to establish a protocol version 3 connection to " + hostSpec);
@@ -176,8 +191,43 @@
ProtocolConnectionImpl protoConnection = new ProtocolConnectionImpl(newStream, user, database, info, logger);
readStartupMessages(newStream, protoConnection, logger);
+ // Check Master or Slaver
+ if(targetServerType.equals("any")){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectOK);
+ }else if(targetServerType.equals("master")){
+ if(isMaster(protoConnection, logger)){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Master);
+ }else{
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Slave);
+ protoConnection.close();
+ if (hostIter.hasNext()) {
+ // still more addresses to try
+ continue;
+ }
+ throw new PSQLException (GT.tr("Couldn't find a server with specified targetServerType: {0}", targetServerType) , PSQLState.CONNECTION_UNABLE_TO_CONNECT);
+ }
+ }else if(targetServerType.equals("slave")){
+ if(isMaster(protoConnection, logger)){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Master);
+ protoConnection.close();
+ if (hostIter.hasNext()) {
+ // still more addresses to try
+ continue;
+ }
+ throw new PSQLException (GT.tr("Couldn't find a server with specified targetServerType: {0}", targetServerType) , PSQLState.CONNECTION_UNABLE_TO_CONNECT);
+ }else{
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Slave);
+ }
+ }else{//slaveFirst
+ if(isMaster(protoConnection, logger)){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Master);
+ }else{
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Slave);
+ }
+ }
+
runInitialQueries(protoConnection, info, logger);
-
+
// And we're done.
return protoConnection;
}
@@ -193,6 +243,7 @@
catch (IOException e)
{
}
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectFail);
return null;
}
catch (ConnectException cex)
@@ -200,7 +251,9 @@
// Added by Peter Mount <peter@retep.org.uk>
// ConnectException is thrown when the connection cannot be made.
// we trap this an return a more meaningful message for the end user
- if (whichHost + 1 < hostSpecs.length) {
+
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectFail);
+ if (hostIter.hasNext()) {
// still more addresses to try
continue;
}
@@ -218,7 +271,8 @@
{
}
}
- if (whichHost + 1 < hostSpecs.length) {
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectFail);
+ if (hostIter.hasNext()) {
// still more addresses to try
continue;
}
@@ -236,7 +290,8 @@
{
}
}
- if (whichHost + 1 < hostSpecs.length) {
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectFail);
+ if (hostIter.hasNext()) {
// still more addresses to try
continue;
}
@@ -646,5 +701,11 @@
}
}
+
+ private boolean isMaster(ProtocolConnectionImpl protoConnection, Logger logger)throws SQLException, IOException {
+ byte[][] results = SetupQueryRunner.run(protoConnection, "show transaction_read_only", true);
+ String value = protoConnection.getEncoding().decode(results[0]);
+ return value.equalsIgnoreCase("off");
+ }
}
diff --git a/org/postgresql/ds/common/BaseDataSource.java b/org/postgresql/ds/common/BaseDataSource.java
index bfe54f7..0a00e69 100644
--- a/org/postgresql/ds/common/BaseDataSource.java
+++ b/org/postgresql/ds/common/BaseDataSource.java
@@ -63,6 +63,9 @@
private int logLevel = 0;
private int protocolVersion = 0;
private String applicationName;
+ private String targetServerType;
+ private boolean enableLoadBalance = false;
+ private int failedHostCheckPeriod = -1;
/**
* Gets a connection to the PostgreSQL database. The database is identified by the
@@ -397,7 +400,37 @@
{
return applicationName;
}
+
+ public void setTargetServerType(String targetServerType)
+ {
+ this.targetServerType = targetServerType;
+ }
+
+ public String getTargetServerType()
+ {
+ return targetServerType;
+ }
+
+ public void setEnableLoadBalance(boolean enableLoadBalance)
+ {
+ this.enableLoadBalance = enableLoadBalance;
+ }
+ public boolean getEnableLoadBalance()
+ {
+ return enableLoadBalance;
+ }
+
+ public void setFailedHostCheckPeriod(int failedHostCheckPeriod)
+ {
+ this.failedHostCheckPeriod = failedHostCheckPeriod;
+ }
+
+ public int getFailedHostCheckPeriod()
+ {
+ return failedHostCheckPeriod;
+ }
+
public void setTcpKeepAlive(boolean enabled)
{
tcpKeepAlive = enabled;
@@ -513,6 +546,16 @@
if (binaryTransfer) {
sb.append("&binaryTransfer=true");
}
+ if (targetServerType != null) {
+ sb.append("&targetServerType=");
+ sb.append(targetServerType);
+ }
+ if (enableLoadBalance) {
+ sb.append("&enableLoadBalance=true");
+ }
+ if (failedHostCheckPeriod != -1) {
+ sb.append("&failedHostCheckPeriod=").append(failedHostCheckPeriod);
+ }
return sb.toString();
}
@@ -565,6 +608,10 @@
ref.add(new StringRefAddr("logLevel", Integer.toString(logLevel)));
ref.add(new StringRefAddr("protocolVersion", Integer.toString(protocolVersion)));
ref.add(new StringRefAddr("ApplicationName", applicationName));
+
+ ref.add(new StringRefAddr("targetServerType", targetServerType));
+ ref.add(new StringRefAddr("enableLoadBalance", Boolean.toString(enableLoadBalance)));
+ ref.add(new StringRefAddr("failedHostCheckPeriod", Integer.toString(failedHostCheckPeriod)));
return ref;
}
@@ -592,6 +639,9 @@
out.writeBoolean(binaryTransfer);
out.writeObject(binaryTransferEnable);
out.writeObject(binaryTransferDisable);
+ out.writeObject(targetServerType);
+ out.writeBoolean(enableLoadBalance);
+ out.writeInt(failedHostCheckPeriod);
}
protected void readBaseObject(ObjectInputStream in) throws IOException, ClassNotFoundException
@@ -617,6 +667,9 @@
binaryTransfer = in.readBoolean();
binaryTransferEnable = (String)in.readObject();
binaryTransferDisable = (String)in.readObject();
+ targetServerType = (String)in.readObject();
+ enableLoadBalance = in.readBoolean();
+ failedHostCheckPeriod = in.readInt();
}
public void initializeFrom(BaseDataSource source) throws IOException, ClassNotFoundException {
diff --git a/org/postgresql/hostchooser/HostChooser.java b/org/postgresql/hostchooser/HostChooser.java
new file mode 100644
index 0000000..fa1e1a9
--- /dev/null
+++ b/org/postgresql/hostchooser/HostChooser.java
@@ -0,0 +1,16 @@
+/**
+ *
+ */
+package org.postgresql.hostchooser;
+
+import java.util.Iterator;
+
+import org.postgresql.util.HostSpec;
+
+/**
+ *
+ */
+public interface HostChooser {
+ Iterator<HostSpec> iterator();
+ void reportHostStatus(HostSpec hostSpec, HostStatus hostStatus);
+}
diff --git a/org/postgresql/hostchooser/HostChooserFactory.java b/org/postgresql/hostchooser/HostChooserFactory.java
new file mode 100644
index 0000000..0cf4461
--- /dev/null
+++ b/org/postgresql/hostchooser/HostChooserFactory.java
@@ -0,0 +1,26 @@
+/**
+ *
+ */
+package org.postgresql.hostchooser;
+
+import java.util.Properties;
+import org.postgresql.util.HostSpec;
+
+/**
+ *
+ */
+public class HostChooserFactory {
+
+ public static HostChooser createHostChooser(HostSpec[] hostSpecs,Properties info){
+
+ if(hostSpecs.length==1){
+ return new SingleHostChooser(hostSpecs[0]);
+ }
+
+ if (Boolean.valueOf(info.getProperty("enableLoadBalance","false")).booleanValue()){
+ return new LoadBalanceHostChooser(hostSpecs,info);
+ }
+
+ return new LastKnownGoodHostChooser(hostSpecs,info);
+ }
+}
diff --git a/org/postgresql/hostchooser/HostChooserWithStatusReport.java b/org/postgresql/hostchooser/HostChooserWithStatusReport.java
new file mode 100644
index 0000000..f0756b4
--- /dev/null
+++ b/org/postgresql/hostchooser/HostChooserWithStatusReport.java
@@ -0,0 +1,48 @@
+package org.postgresql.hostchooser;
+
+import java.util.HashMap;
+
+import org.postgresql.util.*;
+
+/*
+ * Abstract class which implements host status reporting
+ *
+ * @author Chen Huajun (chenhj@cn.fujitsu.com)
+ */
+public abstract class HostChooserWithStatusReport implements HostChooser
+{
+ private static volatile HashMap<String,HostStatus> hostStatusCache = new HashMap<String,HostStatus>();
+
+ protected HashMap<String,HostStatus> hostStatusMap = (HashMap<String, HostStatus>) hostStatusCache.clone();
+
+ public void reportHostStatus(HostSpec hostSpec, HostStatus hostStatus) {
+ reportHostStatus(hostSpec.toString(),hostStatus);
+ }
+
+ private boolean needUpdateHostStatus(HostStatus oldHostStatus,HostStatus newHostStatus){
+ if(oldHostStatus == newHostStatus)
+ return false;
+
+ if(newHostStatus == HostStatus.ConnectOK){
+ if(oldHostStatus == HostStatus.Master ||
+ oldHostStatus == HostStatus.Slave)
+ return false;
+ }
+
+ return true;
+ }
+
+ public void reportHostStatus(String hostSpecKey, HostStatus hostStatus) {
+ HostStatus oldHostStatus = hostStatusCache.get(hostSpecKey);
+ if(needUpdateHostStatus(oldHostStatus, hostStatus)) {
+ synchronized(HostChooserWithStatusReport.class){
+ oldHostStatus = hostStatusCache.get(hostSpecKey);
+ if(needUpdateHostStatus(oldHostStatus, hostStatus)) {
+ HashMap<String,HostStatus> newHostStatusMap = (HashMap<String, HostStatus>) hostStatusCache.clone();
+ newHostStatusMap.put(hostSpecKey, hostStatus);
+ hostStatusCache=newHostStatusMap;
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/org/postgresql/hostchooser/HostStatus.java b/org/postgresql/hostchooser/HostStatus.java
new file mode 100644
index 0000000..42ba31c
--- /dev/null
+++ b/org/postgresql/hostchooser/HostStatus.java
@@ -0,0 +1,14 @@
+/**
+ *
+ */
+package org.postgresql.hostchooser;
+
+/**
+ *
+ */
+public enum HostStatus {
+ ConnectOK,
+ ConnectFail,
+ Master,
+ Slave
+}
diff --git a/org/postgresql/hostchooser/LastKnownGoodHostChooser.java b/org/postgresql/hostchooser/LastKnownGoodHostChooser.java
new file mode 100644
index 0000000..158757c
--- /dev/null
+++ b/org/postgresql/hostchooser/LastKnownGoodHostChooser.java
@@ -0,0 +1,75 @@
+package org.postgresql.hostchooser;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.Properties;
+
+import org.postgresql.util.*;
+
+/*
+ * Pick up one known good host first and then try others
+ *
+ * @author Chen Huajun (chenhj@cn.fujitsu.com)
+ */
+public class LastKnownGoodHostChooser extends HostChooserWithStatusReport
+{
+ private final HostSpec[] hostSpecs;
+ private String targetServerType;
+
+ public LastKnownGoodHostChooser(HostSpec[] hostSpecs,Properties info) {
+ this.hostSpecs = hostSpecs;
+ targetServerType = info.getProperty("targetServerType", "any").toLowerCase();
+ }
+
+ public Iterator<HostSpec> iterator() {
+ int first = -1;
+ for (int i = 0; i < hostSpecs.length; i++) {
+ HostStatus hostStatus = hostStatusMap.get(hostSpecs[i].toString());
+ if(hostStatus != null){
+ if(targetServerType.equals("any") && hostStatus != HostStatus.ConnectFail){
+ first = i;
+ break;
+ }
+
+ if(targetServerType.equals("master") && hostStatus == HostStatus.Master){
+ first = i;
+ break;
+ }
+
+ if((targetServerType.equals("slave") || targetServerType.equals("slavefirst")) &&
+ hostStatus == HostStatus.Slave){
+ first = i;
+ break;
+ }
+ }
+ }
+
+ if(first == -1 && targetServerType.equals("slavefirst")){
+ for (int i = 0; i < hostSpecs.length; i++) {
+ HostStatus hostStatus = hostStatusMap.get(hostSpecs[i].toString());
+ if(hostStatus != null){
+ if(hostStatus != HostStatus.ConnectFail){
+ first = i;
+ break;
+ }
+ }
+ }
+ }
+
+ if (first == -1 ) {
+ first = 0;
+ }
+
+ ArrayList<HostSpec> reordered = new ArrayList<HostSpec>(hostSpecs.length);
+ for (int i = first; i < hostSpecs.length; i++) {
+ reordered.add(hostSpecs[i]);
+ }
+
+ for (int i = 0; i < first; i++) {
+ reordered.add(hostSpecs[i]);
+ }
+
+ return reordered.iterator();
+ }
+
+}
\ No newline at end of file
diff --git a/org/postgresql/hostchooser/LoadBalanceHostChooser.java b/org/postgresql/hostchooser/LoadBalanceHostChooser.java
new file mode 100644
index 0000000..1586e54
--- /dev/null
+++ b/org/postgresql/hostchooser/LoadBalanceHostChooser.java
@@ -0,0 +1,116 @@
+package org.postgresql.hostchooser;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.Properties;
+
+import org.postgresql.util.*;
+
+/*
+ * Pick up one from known good hosts randomly first and then try others
+ *
+ * @author Chen Huajun (chenhj@cn.fujitsu.com)
+ */
+public class LoadBalanceHostChooser extends HostChooserWithStatusReport
+{
+ private final HostSpec[] hostSpecs;
+ private String targetServerType;
+ private int failedHostCheckPeriod;
+ private static long lastfailedHostCheckTime = new Date().getTime();
+
+ public LoadBalanceHostChooser(HostSpec[] hostSpecs,Properties info) {
+ this.hostSpecs = hostSpecs;
+ targetServerType = info.getProperty("targetServerType", "any").toLowerCase();
+ failedHostCheckPeriod = Integer.parseInt(info.getProperty("failedHostCheckPeriod", "600"))*1000;
+ }
+
+ public Iterator<HostSpec> iterator() {
+ long now = new Date().getTime();
+ if(failedHostCheckPeriod >0 && now > lastfailedHostCheckTime + failedHostCheckPeriod)
+ {
+ int connectFailCount = 0;
+ Iterator<String> iter = hostStatusMap.keySet().iterator();
+ while(iter.hasNext()){
+ String key = iter.next();
+ if(hostStatusMap.get(key) == HostStatus.ConnectFail){
+ connectFailCount++;
+ }
+ }
+
+ if(connectFailCount > 0)
+ {
+ synchronized(HostChooserWithStatusReport.class){
+ if(now > lastfailedHostCheckTime + failedHostCheckPeriod)
+ {
+ iter = hostStatusMap.keySet().iterator();
+ while(iter.hasNext()){
+ String key = iter.next();
+ if(hostStatusMap.get(key) == HostStatus.ConnectFail){
+ reportHostStatus(key, null);
+ }
+ }
+ lastfailedHostCheckTime = now;
+ }
+ }
+ }
+ }
+
+ ArrayList<HostSpec> reordered = new ArrayList<HostSpec>(hostSpecs.length);
+ ArrayList<HostSpec> rest = new ArrayList<HostSpec>(hostSpecs.length);
+ for (int i = 0; i < hostSpecs.length; i++) {
+ rest.add(hostSpecs[i]);
+ HostStatus hostStatus = hostStatusMap.get(hostSpecs[i].toString());
+ if(hostStatus != null){
+ if(targetServerType.equals("any") && hostStatus != HostStatus.ConnectFail){
+ reordered.add(hostSpecs[i]);
+ rest.remove(rest.size()-1);
+ continue;
+ }
+
+ if(targetServerType.equals("master") && hostStatus == HostStatus.Master){
+ reordered.add(hostSpecs[i]);
+ rest.remove(rest.size()-1);
+ continue;
+ }
+
+ if((targetServerType.equals("slave") || targetServerType.equals("slavefirst")) &&
+ hostStatus == HostStatus.Slave){
+ reordered.add(hostSpecs[i]);
+ rest.remove(rest.size()-1);
+ continue;
+ }
+ }else{
+ reordered.add(hostSpecs[i]);
+ rest.remove(rest.size()-1);
+ continue;
+ }
+ }
+
+ if(reordered.size() == 0 && targetServerType.equals("slavefirst")){
+ for (int i = 0; i < hostSpecs.length; i++) {
+ HostStatus hostStatus = hostStatusMap.get(hostSpecs[i].toString());
+ if(hostStatus != null){
+ if(hostStatus != HostStatus.ConnectFail){
+ reordered.add(hostSpecs[i]);
+ rest.remove(hostSpecs[i]);
+ }
+ }
+ }
+ }
+
+ if (reordered.size() > 0) {
+ int first = (int)(Math.random() * reordered.size());
+ HostSpec tmpHostSpec=reordered.get(0);
+ reordered.set(0, reordered.get(first));
+ reordered.set(first,tmpHostSpec);
+ }
+
+ for (int i = 0; i < rest.size(); i++) {
+ reordered.add(rest.get(i));
+ }
+
+ return reordered.iterator();
+ }
+
+}
\ No newline at end of file
diff --git a/org/postgresql/hostchooser/SingleHostChooser.java b/org/postgresql/hostchooser/SingleHostChooser.java
new file mode 100644
index 0000000..08635b8
--- /dev/null
+++ b/org/postgresql/hostchooser/SingleHostChooser.java
@@ -0,0 +1,21 @@
+package org.postgresql.hostchooser;
+
+import java.util.Collections;
+import java.util.Iterator;
+
+import org.postgresql.util.*;
+
+public class SingleHostChooser implements HostChooser {
+ private final HostSpec hostSpec;
+
+ public SingleHostChooser(HostSpec hostSpec) {
+ this.hostSpec = hostSpec;
+ }
+
+ public Iterator<HostSpec> iterator() {
+ return Collections.singletonList(hostSpec).iterator();
+ }
+
+ public void reportHostStatus(HostSpec hostSpec, HostStatus hostStatus) {
+ }
+}
\ No newline at end of file=
MutiHostsConnectionTest.java (text/java, 10.6K) download
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.postgresql.ds.PGConnectionPoolDataSource;
import junit.framework.Assert;
//master 127.0.0.1:5432
//slave 127.0.0.1:5433
public class MutiHostsConnectionTest {
public static String getServerInfo(Connection con) throws SQLException{
ResultSet rs = con.createStatement().executeQuery("select inet_server_addr(),inet_server_port()");
rs.next();
String hostspec = rs.getString(1)+":"+rs.getString(2);
return hostspec;
}
public static void testFailOver() throws SQLException{
System.out.println("");
System.out.println("");
System.out.println("test()");
Connection con;
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
String url = "jdbc:postgresql://127.0.0.1:5433,notahost:0001/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertEquals("127.0.0.1:5433", getServerInfo(con));
con.close();
url = "jdbc:postgresql://notahost:0002,127.0.0.1:5433/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertEquals("127.0.0.1:5433", getServerInfo(con));
con.close();
url = "jdbc:postgresql://127.0.0.1:5432,127.0.0.1:5433/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
con.close();
//test targetServerType=Any
props.setProperty("targetServerType", "Any");
url = "jdbc:postgresql://127.0.0.1:5432,127.0.0.1:5433/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
con.close();
//test targetServerType=Master
props.setProperty("targetServerType", "Master");
url = "jdbc:postgresql://127.0.0.1:5432,127.0.0.1:5433/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertTrue(isMaster(con));
con.close();
//test targetServerType=Slave
props.setProperty("targetServerType", "Slave");
url = "jdbc:postgresql://127.0.0.1:5433,127.0.0.1:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertFalse(isMaster(con));
con.close();
//test targetServerType=SlaveFirst
props.setProperty("targetServerType", "SlaveFirst");
url = "jdbc:postgresql://127.0.0.1:5433,127.0.0.1:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertFalse(isMaster(con));
con.close();
props.setProperty("targetServerType", "SlaveFirst");
url = "jdbc:postgresql://notahost:0001,127.0.0.1:5433/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertEquals("127.0.0.1:5433", getServerInfo(con));
con.close();
props.setProperty("targetServerType", "SlaveFirst");
url = "jdbc:postgresql://notahost:0001,127.0.0.1:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertEquals("127.0.0.1:5432", getServerInfo(con));
con.close();
}
public static void testLoadBalance() throws SQLException{
System.out.println("");
System.out.println("");
System.out.println("testLoadBalance()");
Connection con;
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
props.setProperty("enableLoadBalance", "true");
String url = "jdbc:postgresql://127.0.0.1:5433,localhost:5433,notahost:0001,127.0.0.1:5432,localhost:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
con.close();
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
con.close();
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
con.close();
//test targetServerType=Any
props.setProperty("targetServerType", "Any");
url = "jdbc:postgresql://127.0.0.1:5433,localhost:5433,notahost:0001,127.0.0.1:5432,localhost:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
con.close();
//test targetServerType=Master
props.setProperty("targetServerType", "Master");
url = "jdbc:postgresql://127.0.0.1:5433,localhost:5433,notahost:0001,127.0.0.1:5432,localhost:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertTrue(isMaster(con));
con.close();
//test targetServerType=Slave
props.setProperty("targetServerType", "Slave");
url = "jdbc:postgresql://127.0.0.1:5433,localhost:5433,notahost:0001,127.0.0.1:5432,localhost:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertFalse(isMaster(con));
con.close();
//test targetServerType=Slave
props.setProperty("targetServerType", "Slave");
url = "jdbc:postgresql://127.0.0.1:5433,localhost:5433,notahost:0001,localhost:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertFalse(isMaster(con));
con.close();
//test targetServerType=SlaveFirst
props.setProperty("targetServerType", "SlaveFirst");
url = "jdbc:postgresql://127.0.0.1:5433,localhost:5433,notahost:0001,127.0.0.1:5433,localhost:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertFalse(isMaster(con));
con.close();
props.setProperty("targetServerType", "SlaveFirst");
url = "jdbc:postgresql://127.0.0.1:5433,localhost:5433,notahost:0001/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertEquals("127.0.0.1:5433", getServerInfo(con));
con.close();
props.setProperty("targetServerType", "SlaveFirst");
url = "jdbc:postgresql://127.0.0.1:5432,localhost:5432,notahost:0001/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertEquals("127.0.0.1:5432", getServerInfo(con));
con.close();
}
public static void testLoadBalanceWithFailedReCheck() throws SQLException, IOException{
System.out.println("");
System.out.println("");
System.out.println("testLoadBalanceWithFailedReCheck()");
Connection con;
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
props.setProperty("enableLoadBalance", "true");
props.setProperty("failedHostCheckPeriod", "3");
props.setProperty("targetServerType", "SlaveFirst");
System.out.println("Stop the slave and press enter");
System.in.read();
System.in.read();
String url = "jdbc:postgresql://127.0.0.1:5432,127.0.0.1:5433/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
Assert.assertTrue(isMaster(con));
con.close();
System.out.println("Start the slave and press enter after 5 seconds");
System.in.read();
System.in.read();
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
con.close();
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
Assert.assertFalse(isMaster(con));
con.close();
}
public static void testURL() throws SQLException{
System.out.println("");
System.out.println("");
System.out.println("testURL()");
Connection con;
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
String url = "jdbc:postgresql://127.0.0.1:5432,127.0.0.1:5433/postgres?targetServerType=master";
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
Assert.assertTrue(isMaster(con));
con.close();
url = "jdbc:postgresql://127.0.0.1:5432,127.0.0.1:5433/postgres?targetServerType=slave";
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
Assert.assertFalse(isMaster(con));
con.close();
}
public static boolean isMaster(Connection con) throws SQLException{
ResultSet rs = con.createStatement().executeQuery("show transaction_read_only");
rs.next();
return "off".equalsIgnoreCase(rs.getString(1));
}
public static String protocolVersion = "";
public static String user = "chj";
public static String password = "postgres";
/**
* @param args
*/
public static void main(String[] args) {
try {
Class.forName("org.postgresql.Driver");
protocolVersion = "?protocolVersion=3";
testFailOver();
testLoadBalance();
testURL();
//testLoadBalanceWithFailedReCheck();
System.out.println("OK");
} catch (Exception e) {
e.printStackTrace();
}
}
}
view thread (13+ messages) latest in thread
Message-ID: <50D82DD5.5020903@cn.fujitsu.com>
Permalink: ../50D82DD5.5020903@cn.fujitsu.com/
Also on: postgresql.org/message-id/50D82DD5.5020903@cn.fujitsu.com
copy link · copy postgr.es · copy git am
reply Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-jdbc@postgresql.org
Cc: chenhj@cn.fujitsu.com
Subject: Re: performance problem of Failover Datasource?
In-Reply-To: <50D82DD5.5020903@cn.fujitsu.com>
References: <4DFA5A86.9030301@acm.org> <itdn5g$eu7$1@dough.gmane.org> <4DFA671F.2050005@acm.org> <4DFA9704.4000209@hogranch.com> <4DFAB403.5010309@acm.org> <4DFAB5B8.5010603@hogranch.com> <4DFAB9E2.4070905@acm.org> <1334056170219-5629626.post@n5.nabble.com> <1355303340886-5736270.post@n5.nabble.com> <50C9B102.2060208@cn.fujitsu.com> <CADK3HH+TLPjrrJ=cQWqZ+0B5o96xR+sTVcvqhcDU4CjyryKG2g@mail.gmail.com> <50CA959E.4060603@cn.fujitsu.com> <50CB29BD.6090903@cn.fujitsu.com> <50CC2279.3090301@cn.fujitsu.com> <alpine.WNT.2.00.1212151055200.6544@turks> <50CFB362.4080701@cn.fujitsu.com> <50D82DD5.5020903@cn.fujitsu.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox