diff --git a/src/main/java/com/alibaba/druid/pool/ha/DataSourceChangedEvent.java b/src/main/java/com/alibaba/druid/pool/ha/DataSourceChangedEvent.java deleted file mode 100644 index b256ce4577..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/DataSourceChangedEvent.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha; - -import com.alibaba.druid.pool.DruidDataSource; - -public class DataSourceChangedEvent { - - private final DruidDataSource dataSource; - - public DataSourceChangedEvent(DruidDataSource dataSource){ - this.dataSource = dataSource; - } - - public DruidDataSource getDataSource() { - return dataSource; - } - -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/DataSourceHolder.java b/src/main/java/com/alibaba/druid/pool/ha/DataSourceHolder.java deleted file mode 100644 index c3d86a1ee9..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/DataSourceHolder.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha; - -import java.io.Closeable; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.concurrent.atomic.AtomicLong; - -import com.alibaba.druid.pool.DruidDataSource; - -public class DataSourceHolder implements Closeable { - - private final MultiDataSource multiDataSource; - private final DruidDataSource dataSource; - private boolean enable = true; - private final AtomicLong connectCount = new AtomicLong(); - private final AtomicLong connectErrorCount = new AtomicLong(); - - private boolean fail = false; - - private int weight = 1; - - private transient int weightRegionBegin; - - private transient int weightRegionEnd; - - private boolean writable = true; - - public boolean isWritable() { - return writable; - } - - public void setWritable(boolean writable) { - this.writable = writable; - } - - public int getWeightRegionBegin() { - return weightRegionBegin; - } - - public void setWeightRegionBegin(int weightRegionBegin) { - this.weightRegionBegin = weightRegionBegin; - } - - public int getWeightRegionEnd() { - return weightRegionEnd; - } - - public void setWeightRegionEnd(int weightReginEnd) { - this.weightRegionEnd = weightReginEnd; - } - - public DataSourceHolder(MultiDataSource multiDataSource, DruidDataSource dataSource){ - if (dataSource == null) { - throw new IllegalArgumentException("dataSource is null"); - } - this.multiDataSource = multiDataSource; - this.dataSource = dataSource; - } - - public void resetState() { - connectCount.set(0); - } - - public int getWeight() { - return weight; - } - - public void setWeight(int weight) { - this.weight = weight; - } - - public boolean isEnable() { - return enable && (!fail); - } - - public void setEnable(boolean enable) { - if (this.enable != enable) { - this.enable = enable; - - multiDataSource.afterDataSourceChanged(null); - } - } - - public boolean isFail() { - return fail; - } - - public void setFail(boolean fail) { - if (this.fail != fail) { - this.fail = fail; - multiDataSource.afterDataSourceChanged(null); - } - } - - public DruidDataSource getDataSource() { - return dataSource; - } - - public long getConnectCount() { - return connectCount.get(); - } - - public void incrementConnectCount() { - connectCount.incrementAndGet(); - } - - public String getUrl() { - return dataSource.getUrl(); - } - - public MultiConnectionHolder getConnection() throws SQLException { - connectCount.incrementAndGet(); - try { - Connection conn = dataSource.getConnection(); - - return new MultiConnectionHolder(this, conn); - } catch (SQLException ex) { - connectErrorCount.incrementAndGet(); - throw ex; - } catch (RuntimeException ex) { - connectErrorCount.incrementAndGet(); - throw ex; - } - } - - @Override - public void close() { - dataSource.close(); - } - - public void restart() { - dataSource.restart(); - } -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/HADataSource.java b/src/main/java/com/alibaba/druid/pool/ha/HADataSource.java deleted file mode 100644 index 9f10e3cf07..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/HADataSource.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha; - -import javax.sql.DataSource; - -import com.alibaba.druid.pool.DruidDataSource; -import com.alibaba.druid.pool.ManagedDataSource; -import com.alibaba.druid.support.logging.Log; -import com.alibaba.druid.support.logging.LogFactory; - -public class HADataSource extends MultiDataSource implements HADataSourceMBean, ManagedDataSource, DataSource { - - private final static Log LOG = LogFactory.getLog(HADataSource.class); - - protected DataSourceHolder master; - protected DataSourceHolder slave; - - public HADataSource(){ - - } - - public void resetStat() { - super.resetStat(); - - master.resetState(); - slave.resetState(); - } - - public boolean isMasterWritable() { - return master != null && master.isWritable(); - } - - public boolean isSlaveWritable() { - return slave != null && slave.isWritable(); - } - - public long getMasterConnectCount() { - return master.getConnectCount(); - } - - public long getSlaveConnectCount() { - return slave.getConnectCount(); - } - - public DataSourceHolder getMaster() { - return master; - } - - public void restartMaster() { - this.restartDataSource("master"); - } - - public void restartSlave() { - this.restartDataSource("slave"); - } - - public DataSourceHolder setMaster(DruidDataSource master) { - DataSourceHolder holder = new DataSourceHolder(this, master); - this.setMaster(holder); - return holder; - } - - public void setMaster(DataSourceHolder master) { - this.addDataSource("master", master); - this.master = master; - } - - public DataSourceHolder getSlave() { - return slave; - } - - public DataSourceHolder setSlave(DruidDataSource slave) { - DataSourceHolder holder = new DataSourceHolder(this, slave); - this.setSlave(holder); - return holder; - } - - public void setSlave(DataSourceHolder slave) { - this.addDataSource("slave", slave); - this.slave = slave; - } - - public boolean isMasterEnable() { - if (master == null) { - return false; - } - - return master.isEnable(); - } - - public boolean isMasterFail() { - if (master == null) { - return false; - } - - return master.isFail(); - } - - public boolean isSlaveFail() { - if (slave == null) { - return false; - } - - return slave.isFail(); - } - - public void setMasterEnable(boolean value) { - if (master == null) { - throw new IllegalStateException("slave is null"); - } - - master.setEnable(value); - - } - - public String getMasterUrl() { - if (master == null) { - return null; - } - - return master.getUrl(); - } - - public String getSlaveUrl() { - if (slave == null) { - return null; - } - - return slave.getUrl(); - } - - public int getMasterWeight() { - return master.getWeight(); - } - - public int getSlaveWeight() { - return slave.getWeight(); - } - - public int getMasterWeightRegionBegin() { - return master.getWeightRegionBegin(); - } - - public int getMasterWeightRegionEnd() { - return master.getWeightRegionEnd(); - } - - public int getSlaveWeightRegionBegin() { - return slave.getWeightRegionBegin(); - } - - public int getSlaveWeightRegionEnd() { - return slave.getWeightRegionEnd(); - } - - public boolean isSlaveEnable() { - if (slave == null) { - return false; - } - - return slave.isEnable(); - } - - public void setSlaveEnable(boolean value) { - if (slave == null) { - throw new IllegalStateException("slave is null"); - } - - slave.setEnable(value); - } - - public void switchMasterSlave() { - DataSourceHolder tmp = this.getMaster(); - this.setMaster(this.getSlave()); - this.setSlave(tmp); - } - - public void close() { - super.close(); - if (LOG.isDebugEnabled()) { - LOG.debug("HADataSource closed"); - } - } -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/HADataSourceMBean.java b/src/main/java/com/alibaba/druid/pool/ha/HADataSourceMBean.java deleted file mode 100644 index 11fb2a2540..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/HADataSourceMBean.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha; - -public interface HADataSourceMBean extends MultiDataSourceMBean { - long getMasterConnectCount(); - - long getSlaveConnectCount(); - - boolean isMasterEnable(); - - void setMasterEnable(boolean value); - - boolean isSlaveEnable(); - - void setSlaveEnable(boolean value); - - String getMasterUrl(); - - String getSlaveUrl(); - - void switchMasterSlave(); - - void resetStat(); - - void restartMaster(); - - void restartSlave(); - - boolean isMasterFail(); - - boolean isSlaveFail(); - - int getMasterWeight(); - - int getSlaveWeight(); - - int getMasterWeightRegionBegin(); - - int getMasterWeightRegionEnd(); - - int getSlaveWeightRegionBegin(); - - int getSlaveWeightRegionEnd(); -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/MultiConnectionHolder.java b/src/main/java/com/alibaba/druid/pool/ha/MultiConnectionHolder.java deleted file mode 100644 index c67ff9a384..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/MultiConnectionHolder.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha; - -import java.sql.Connection; - -public class MultiConnectionHolder { - - private final Connection connection; - private final DataSourceHolder dataSourceHolder; - - public MultiConnectionHolder(DataSourceHolder dataSourceHolder, Connection connection){ - super(); - this.dataSourceHolder = dataSourceHolder; - this.connection = connection; - } - - public Connection getConnection() { - return connection; - } - - public DataSourceHolder getDataSourceHolder() { - return dataSourceHolder; - } - -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/MultiDataSource.java b/src/main/java/com/alibaba/druid/pool/ha/MultiDataSource.java deleted file mode 100644 index 2cf4235f7a..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/MultiDataSource.java +++ /dev/null @@ -1,529 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha; - -import java.sql.Connection; -import java.sql.Driver; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import javax.management.ObjectName; - -import com.alibaba.druid.filter.Filter; -import com.alibaba.druid.pool.DataSourceAdapter; -import com.alibaba.druid.pool.ha.balance.Balancer; -import com.alibaba.druid.pool.ha.balance.WeightBalancer; -import com.alibaba.druid.pool.ha.config.ConfigLoader; -import com.alibaba.druid.pool.ha.valid.DataSourceFailureDetecter; -import com.alibaba.druid.pool.ha.valid.DefaultDataSourceFailureDetecter; -import com.alibaba.druid.proxy.jdbc.DataSourceProxy; -import com.alibaba.druid.stat.JdbcDataSourceStat; -import com.alibaba.druid.support.logging.Log; -import com.alibaba.druid.support.logging.LogFactory; -import com.alibaba.druid.util.JdbcUtils; - -public class MultiDataSource extends DataSourceAdapter implements MultiDataSourceMBean, DataSourceProxy { - - private final static Log LOG = LogFactory.getLog(MultiDataSource.class); - - private Properties properties = new Properties(); - - private final AtomicLong connectionIdSeed = new AtomicLong(); - private final AtomicLong statementIdSeed = new AtomicLong(); - private final AtomicLong resultSetIdSeed = new AtomicLong(); - private final AtomicLong transactionIdSeed = new AtomicLong(); - - private final AtomicLong configLoadCount = new AtomicLong(); - private final AtomicLong failureDetectCount = new AtomicLong(); - - private final AtomicLong busySkipCount = new AtomicLong(); - private final AtomicLong retryGetConnectionCount = new AtomicLong(); - - protected DataSourceFailureDetecter failureDetector = new DefaultDataSourceFailureDetecter(); - private long failureDetectPeriodMillis = 3000; - private long configLoadPeriodMillis = 1000 * 60; - - private int schedulerThreadCount = 3; - private ScheduledExecutorService scheduler; - - private ScheduledFuture failureDetectFuture; - private ScheduledFuture configLoadFuture; - - private boolean inited = false; - protected final Lock lock = new ReentrantLock(); - protected final Condition notFull = lock.newCondition(); - protected final Condition notFail = lock.newCondition(); - - private ConcurrentMap dataSources = new ConcurrentHashMap(); - - private ObjectName objectName; - - private List filters = new ArrayList(); - - private boolean enable; - - private String name; - - private ConfigLoader configLoader; - - private int maxPoolSize = 50; - - private long activeCount = 0; - private long maxWaitMillis = 0; - - private Balancer balancer = new WeightBalancer(); - - private JdbcDataSourceStat dataSourceStat; - - protected Properties connectionProperties = new Properties(); - - public long getMaxWaitMillis() { - return maxWaitMillis; - } - - public void setMaxWaitMillis(long maxWaitMillis) { - this.maxWaitMillis = maxWaitMillis; - } - - public void setMaxWait(long seconds) { - this.setMaxWaitMillis(1000 * seconds); - } - - public long getMaxWait() { - return this.getMaxWaitMillis() / 1000; - } - - public int getMaxPoolSize() { - return maxPoolSize; - } - - public void setMaxPoolSize(int maxPoolSize) throws SQLException { - if (this.isIntited()) { - throw new SQLException("dataSource inited"); - } - - this.maxPoolSize = maxPoolSize; - } - - public ConfigLoader getConfigLoader() { - return configLoader; - } - - public void setConfigLoader(ConfigLoader configLoader) { - this.configLoader = configLoader; - } - - public String getName() { - if (name == null) { - return "HADataSource-" + System.identityHashCode(this); - } - return name; - } - - public String getNameInternal() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - public boolean isIntited() { - return this.inited; - } - - public boolean isEnable() { - return enable; - } - - public void setEnable(boolean enable) { - this.enable = enable; - } - - public ObjectName getObjectName() { - return objectName; - } - - public void setObjectName(ObjectName objectName) { - this.objectName = objectName; - } - - public MultiDataSource(){ - - } - - public void init() throws SQLException { - if (inited) { - return; - } - - lock.lock(); - try { - if (inited) { - return; - } - - dataSourceStat = new JdbcDataSourceStat(name, null); - - this.balancer.init(this); - - initInternal(); - - scheduler = Executors.newScheduledThreadPool(schedulerThreadCount); - startFailureDetectScheduleTask(); - startConfigLoadScheduleTask(); - inited = true; - - MultiDataSourceStatManager.add(this); - } finally { - lock.unlock(); - } - } - - public boolean startConfigLoadScheduleTask() { - if (configLoadFuture == null) { - configLoadFuture = scheduler.scheduleAtFixedRate(new ConfigLoadTask(), configLoadPeriodMillis, - configLoadPeriodMillis, TimeUnit.MILLISECONDS); - return true; - } - - return false; - } - - public boolean stopConfigLoadScheduleTask() { - if (configLoadFuture != null) { - configLoadFuture.cancel(true); - configLoadFuture = null; - return true; - } - - return false; - } - - public boolean startFailureDetectScheduleTask() { - if (failureDetectFuture == null) { - failureDetectFuture = scheduler.scheduleAtFixedRate(new FailureDetectTask(), failureDetectPeriodMillis, - failureDetectPeriodMillis, TimeUnit.MILLISECONDS); - return true; - } - - return false; - } - - public boolean stopFailureDetectScheduleTask() { - if (failureDetectFuture != null) { - failureDetectFuture.cancel(true); - failureDetectFuture = null; - return true; - } - - return false; - } - - protected void initInternal() throws SQLException { - - } - - public void resetStat() { - - } - - public void close() { - if (scheduler != null) { - scheduler.shutdownNow(); - } - - Object[] items = this.getDataSources().values().toArray(); - for (Object item : items) { - JdbcUtils.close((DataSourceHolder) item); - } - - MultiDataSourceStatManager.remove(this); - } - - public void failureDetect() { - int changeCount = 0; - for (DataSourceHolder dataSourceHolder : getDataSources().values()) { - boolean isFail = !failureDetector.isValid(dataSourceHolder.getDataSource()); - - if (isFail != dataSourceHolder.isFail()) { - dataSourceHolder.setFail(isFail); - changeCount++; - } - } - if (changeCount != 0) { - afterDataSourceChanged(null); - } - - failureDetectCount.incrementAndGet(); - } - - protected ScheduledExecutorService getScheduler() { - return scheduler; - } - - public void setFailureDetectPeriodMillis(long failureDetectPeriodMillis) { - this.failureDetectPeriodMillis = failureDetectPeriodMillis; - } - - public void setConfigLoadPeriodMillis(long configLoadPeriodMillis) { - this.configLoadPeriodMillis = configLoadPeriodMillis; - } - - public DataSourceFailureDetecter getFailureDetector() { - return failureDetector; - } - - public void setFailureDetector(DataSourceFailureDetecter failureDetector) { - this.failureDetector = failureDetector; - } - - public long createConnectionId() { - return connectionIdSeed.getAndIncrement(); - } - - public long createStatementId() { - return statementIdSeed.incrementAndGet(); - } - - public Map getDataSources() { - return dataSources; - } - - public DataSourceHolder getDataSourceHolder(String name) { - return dataSources.get(name); - } - - public void addDataSource(String name, DataSourceHolder dataSourceHolder) { - dataSources.put(name, dataSourceHolder); - - afterDataSourceChanged(null); - } - - public Properties getProperties() { - return properties; - } - - public long getActiveCount() { - return activeCount; - } - - public void notFailSignal() { - lock.lock(); - try { - notFail.signalAll(); - } finally { - lock.unlock(); - } - } - - public void afterDataSourceChanged(Object event) { - if (!this.balancer.isInited()) { - this.balancer.init(this); - } - - this.balancer.afterDataSourceChanged(null); - } - - public Connection getConnection() throws SQLException { - init(); - - lock.lock(); - try { - if (activeCount >= maxPoolSize) { - notFull.await(); - } - - MultiDataSourceConnection conn = new MultiDataSourceConnection(this, createConnectionId()); - - activeCount++; - - return conn; - } catch (InterruptedException e) { - throw new SQLException("thread interrupted", e); - } finally { - lock.unlock(); - } - } - - protected void afterConnectionClosed(MultiDataSourceConnection conn) { - lock.lock(); - try { - activeCount--; - notFull.signal(); - } finally { - lock.unlock(); - } - } - - public MultiConnectionHolder getRealConnection(MultiDataSourceConnection multiConn, String sql) throws SQLException { - return balancer.getConnection(multiConn, sql); - } - - public int getEnabledDataSourceCount() { - int count = 0; - for (DataSourceHolder item : this.dataSources.values()) { - if (item.isEnable()) { - count++; - } - } - return count; - } - - public void handleNotAwailableDatasource(DataSourceHolder dataSourceHolder) { - } - - public long getRetryGetConnectionCount() { - return retryGetConnectionCount.get(); - } - - public void incrementRetryGetConnectionCount() { - retryGetConnectionCount.incrementAndGet(); - } - - public Lock getLock() { - return lock; - } - - public Condition getNotFail() { - return notFail; - } - - public long getBusySkipCount() { - return busySkipCount.get(); - } - - public void incrementBusySkipCount() { - busySkipCount.incrementAndGet(); - } - - public String[] getDataSourceNames() { - return this.dataSources.keySet().toArray(new String[this.dataSources.size()]); - } - - @Override - public String getDbType() { - return null; - } - - @Override - public Driver getRawDriver() { - return null; - } - - @Override - public String getUrl() { - return null; - } - - @Override - public String getRawJdbcUrl() { - return null; - } - - @Override - public List getProxyFilters() { - return filters; - } - - @Override - public long createResultSetId() { - return resultSetIdSeed.incrementAndGet(); - } - - @Override - public long createTransactionId() { - return transactionIdSeed.incrementAndGet(); - } - - public boolean restartDataSource(String name) { - DataSourceHolder holder = this.getDataSources().get(name); - if (holder != null) { - holder.restart(); - return true; - } - - return false; - } - - public long getConfigLoadCount() { - return configLoadCount.get(); - } - - public long getFailureDetectCount() { - return failureDetectCount.get(); - } - - public long getFailureDetectPeriodMillis() { - return failureDetectPeriodMillis; - } - - public long getConfigLoadPeriodMillis() { - return configLoadPeriodMillis; - } - - class ConfigLoadTask implements Runnable { - - @Override - public void run() { - if (configLoader != null) { - try { - configLoadCount.incrementAndGet(); - configLoader.load(); - } catch (Exception e) { - LOG.error("config load error", e); - } - } - } - } - - class FailureDetectTask implements Runnable { - - @Override - public void run() { - try { - failureDetect(); - } catch (Exception ex) { - LOG.error("failure detect error", ex); - } - } - - } - - @Override - public JdbcDataSourceStat getDataSourceStat() { - return dataSourceStat; - } - - @Override - public Properties getConnectProperties() { - return connectionProperties; - } - -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourceConnection.java b/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourceConnection.java deleted file mode 100644 index 846d7d5d96..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourceConnection.java +++ /dev/null @@ -1,687 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha; - -import java.sql.Array; -import java.sql.Blob; -import java.sql.CallableStatement; -import java.sql.Clob; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.NClob; -import java.sql.PreparedStatement; -import java.sql.SQLClientInfoException; -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; -import java.sql.SQLWarning; -import java.sql.SQLXML; -import java.sql.Savepoint; -import java.sql.Statement; -import java.sql.Struct; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.Executor; - -import com.alibaba.druid.pool.WrapperAdapter; -import com.alibaba.druid.proxy.jdbc.CallableStatementProxyImpl; -import com.alibaba.druid.proxy.jdbc.ConnectionProxy; -import com.alibaba.druid.proxy.jdbc.DataSourceProxy; -import com.alibaba.druid.proxy.jdbc.TransactionInfo; - -public class MultiDataSourceConnection extends WrapperAdapter implements Connection, ConnectionProxy { - - private final MultiDataSource multiDataSource; - - private Connection conn; - private DataSourceHolder dataSourceHolder; - - private final long id; - - private Boolean autoCommit = null; - private Boolean readOnly = null; - private String catalog = null; - private Integer transactionLeval = null; - private Map> typeMap = null; - private Integer holdability = null; - - private Properties clientInfo = null; - - private Map attributes = null; - - private Date connectedTime = null; - - private int closeCount = 0; - - private TransactionInfo transcationInfo; - - public MultiDataSourceConnection(MultiDataSource multiDataSource, long id){ - this.multiDataSource = multiDataSource; - this.id = id; - } - - public DataSourceHolder getDataSourceHolder() { - return dataSourceHolder; - } - - public void checkConnection(String sql) throws SQLException { - if (conn == null) { - MultiConnectionHolder connHolder = multiDataSource.getRealConnection(this, sql); - conn = connHolder.getConnection(); - this.dataSourceHolder = connHolder.getDataSourceHolder(); - } - - if (autoCommit != null) { - conn.setAutoCommit(autoCommit); - } - - if (readOnly != null) { - conn.setReadOnly(readOnly); - } - - if (catalog != null) { - conn.setCatalog(catalog); - } - - if (transactionLeval != null) { - conn.setTransactionIsolation(transactionLeval); - } - - if (typeMap != null) { - conn.setTypeMap(typeMap); - } - - if (holdability != null) { - conn.setHoldability(holdability); - } - - if (clientInfo != null) { - conn.setClientInfo(clientInfo); - } - - connectedTime = new Date(); - } - - public MultiDataSource getMultiDataSource() { - return multiDataSource; - } - - @Override - public String nativeSQL(String sql) throws SQLException { - checkConnection(sql); - - return conn.nativeSQL(sql); - } - - @Override - public void setAutoCommit(boolean autoCommit) throws SQLException { - if (conn != null) { - conn.setAutoCommit(autoCommit); - } else { - this.autoCommit = Boolean.valueOf(autoCommit); - } - - if (!autoCommit) { - if (transcationInfo == null) { - long transactionId = this.getDirectDataSource().createTransactionId(); - transcationInfo = new TransactionInfo(transactionId); - } - } else { - transcationInfo = null; - } - } - - @Override - public boolean getAutoCommit() throws SQLException { - if (conn != null) { - return conn.getAutoCommit(); - } - - if (this.autoCommit != null) { - return this.autoCommit.booleanValue(); - } - - return false; - } - - @Override - public void commit() throws SQLException { - if (conn != null) { - conn.commit(); - } - - if (transcationInfo != null) { - transcationInfo.setEndTimeMillis(); - } - } - - @Override - public void rollback() throws SQLException { - if (conn != null) { - conn.rollback(); - } - - if (transcationInfo != null) { - transcationInfo.setEndTimeMillis(); - } - } - - @Override - public void close() throws SQLException { - if (closeCount > 0) { - closeCount++; - return; - } - - if (conn != null) { - conn.close(); - } - this.closeCount++; - - multiDataSource.afterConnectionClosed(this); - } - - @Override - public boolean isClosed() throws SQLException { - return closeCount > 0; - } - - @Override - public DatabaseMetaData getMetaData() throws SQLException { - if (conn == null) { - throw new SQLException("connection not init"); - } - - return conn.getMetaData(); - } - - @Override - public void setReadOnly(boolean readOnly) throws SQLException { - if (conn != null) { - conn.setReadOnly(readOnly); - } else { - this.readOnly = Boolean.valueOf(readOnly); - } - } - - @Override - public boolean isReadOnly() throws SQLException { - if (conn != null) { - return conn.isReadOnly(); - } - - if (this.readOnly != null) { - return this.readOnly.booleanValue(); - } - - return false; - } - - @Override - public void setCatalog(String catalog) throws SQLException { - if (conn != null) { - conn.setCatalog(catalog); - } else { - this.catalog = catalog; - } - } - - @Override - public String getCatalog() throws SQLException { - if (conn != null) { - return conn.getCatalog(); - } - - return this.catalog; - } - - @Override - public void setTransactionIsolation(int level) throws SQLException { - if (conn != null) { - conn.setTransactionIsolation(level); - } else { - this.transactionLeval = level; - } - } - - @Override - public int getTransactionIsolation() throws SQLException { - if (conn != null) { - return conn.getTransactionIsolation(); - } - - if (this.transactionLeval != null) { - return this.transactionLeval; - } - - return TRANSACTION_NONE; - } - - @Override - public SQLWarning getWarnings() throws SQLException { - if (conn != null) { - return conn.getWarnings(); - } - - return null; - } - - @Override - public void clearWarnings() throws SQLException { - if (conn == null) { - throw new SQLException("connection not init"); - } - - if (conn != null) { - conn.clearWarnings(); - } - } - - @Override - public Map> getTypeMap() throws SQLException { - if (conn != null) { - return conn.getTypeMap(); - } - - return typeMap; - } - - @Override - public void setTypeMap(Map> map) throws SQLException { - if (conn != null) { - conn.setTypeMap(map); - } else { - this.typeMap = map; - } - } - - @Override - public void setHoldability(int holdability) throws SQLException { - if (conn != null) { - conn.setHoldability(holdability); - } else { - this.holdability = holdability; - } - } - - @Override - public int getHoldability() throws SQLException { - if (conn != null) { - return conn.getHoldability(); - } - - if (this.holdability != null) { - return this.holdability; - } - - return 0; - } - - @Override - public Savepoint setSavepoint() throws SQLException { - if (conn == null) { - throw new SQLException("connection not init"); - } - - return conn.setSavepoint(); - } - - @Override - public Savepoint setSavepoint(String name) throws SQLException { - if (conn == null) { - throw new SQLException("connection not init"); - } - - return conn.setSavepoint(name); - } - - @Override - public void rollback(Savepoint savepoint) throws SQLException { - if (conn == null) { - throw new SQLException("connection not init"); - } - - conn.rollback(savepoint); - - if (transcationInfo != null) { - transcationInfo.setEndTimeMillis(); - } - } - - @Override - public void releaseSavepoint(Savepoint savepoint) throws SQLException { - if (conn == null) { - throw new SQLException("connection not init"); - } - - conn.releaseSavepoint(savepoint); - } - - @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { - long stmtId = multiDataSource.createStatementId(); - MultiDataSourceStatement stmt = new MultiDataSourceStatement(this, stmtId, resultSetType, resultSetConcurrency); - return stmt; - } - - @Override - public Statement createStatement() throws SQLException { - long stmtId = multiDataSource.createStatementId(); - MultiDataSourceStatement stmt = new MultiDataSourceStatement(this, stmtId); - return stmt; - } - - @Override - public PreparedStatement prepareStatement(String sql) throws SQLException { - checkConnection(sql); - - PreparedStatement stmt = conn.prepareStatement(sql); - long stmtId = multiDataSource.createStatementId(); - - return new MultiDataSourcePreparedStatement(this, stmt, sql, stmtId); - } - - @Override - public CallableStatement prepareCall(String sql) throws SQLException { - checkConnection(sql); - - CallableStatement stmt = conn.prepareCall(sql); - long stmtId = multiDataSource.createStatementId(); - - return new CallableStatementProxyImpl(this, stmt, sql, stmtId); - } - - @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) - throws SQLException { - checkConnection(sql); - - PreparedStatement stmt = conn.prepareStatement(sql, resultSetType, resultSetConcurrency); - long stmtId = multiDataSource.createStatementId(); - - return new MultiDataSourcePreparedStatement(this, stmt, sql, stmtId); - } - - @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - checkConnection(sql); - - CallableStatement stmt = conn.prepareCall(sql, resultSetType, resultSetConcurrency); - long stmtId = multiDataSource.createStatementId(); - - return new CallableStatementProxyImpl(this, stmt, sql, stmtId); - } - - @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) - throws SQLException { - long stmtId = multiDataSource.createStatementId(); - MultiDataSourceStatement stmt = new MultiDataSourceStatement(this, stmtId, resultSetType, resultSetConcurrency, - resultSetHoldability); - return stmt; - } - - @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability) throws SQLException { - checkConnection(sql); - - PreparedStatement stmt = conn.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - long stmtId = multiDataSource.createStatementId(); - - return new MultiDataSourcePreparedStatement(this, stmt, sql, stmtId); - } - - @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability) throws SQLException { - checkConnection(sql); - - CallableStatement stmt = conn.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - long stmtId = multiDataSource.createStatementId(); - - return new CallableStatementProxyImpl(this, stmt, sql, stmtId); - } - - @Override - public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { - checkConnection(sql); - - PreparedStatement stmt = conn.prepareStatement(sql, autoGeneratedKeys); - long stmtId = multiDataSource.createStatementId(); - - return new MultiDataSourcePreparedStatement(this, stmt, sql, stmtId); - } - - @Override - public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { - checkConnection(sql); - - PreparedStatement stmt = conn.prepareStatement(sql, columnIndexes); - long stmtId = multiDataSource.createStatementId(); - - return new MultiDataSourcePreparedStatement(this, stmt, sql, stmtId); - } - - @Override - public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { - checkConnection(sql); - - PreparedStatement stmt = conn.prepareStatement(sql, columnNames); - long stmtId = multiDataSource.createStatementId(); - - return new MultiDataSourcePreparedStatement(this, stmt, sql, stmtId); - } - - @Override - public Clob createClob() throws SQLException { - if (conn == null) { - throw new SQLException("connection not init"); - } - - return conn.createClob(); - } - - @Override - public Blob createBlob() throws SQLException { - if (conn == null) { - throw new SQLException("connection not init"); - } - - return conn.createBlob(); - } - - @Override - public NClob createNClob() throws SQLException { - if (conn == null) { - throw new SQLException("connection not init"); - } - - return conn.createNClob(); - } - - @Override - public SQLXML createSQLXML() throws SQLException { - if (conn == null) { - throw new SQLException("connection not init"); - } - - return conn.createSQLXML(); - } - - @Override - public boolean isValid(int timeout) throws SQLException { - if (conn == null) { - throw new SQLException("connection not init"); - } - - return conn.isValid(timeout); - } - - @Override - public void setClientInfo(String name, String value) throws SQLClientInfoException { - if (conn != null) { - conn.setClientInfo(name, value); - return; - } - - if (clientInfo == null) { - clientInfo = new Properties(); - } - clientInfo.setProperty(name, value); - } - - @Override - public void setClientInfo(Properties properties) throws SQLClientInfoException { - if (conn != null) { - conn.setClientInfo(properties); - return; - } - - this.clientInfo = properties; - } - - @Override - public String getClientInfo(String name) throws SQLException { - if (conn != null) { - return conn.getClientInfo(name); - } - - if (clientInfo == null) { - return null; - } - - return clientInfo.getProperty(name); - } - - @Override - public Properties getClientInfo() throws SQLException { - if (conn != null) { - return conn.getClientInfo(); - } - - return clientInfo; - } - - @Override - public Array createArrayOf(String typeName, Object[] elements) throws SQLException { - if (conn == null) { - throw new SQLException("connection not init"); - } - - return conn.createArrayOf(typeName, elements); - } - - @Override - public Struct createStruct(String typeName, Object[] attributes) throws SQLException { - if (conn == null) { - throw new SQLException("connection not init"); - } - - return conn.createStruct(typeName, attributes); - } - - // ///// - - @Override - public long getId() { - return id; - } - - @Override - public Connection getRawObject() { - return conn; - } - - @Override - public Map getAttributes() { - if (attributes == null) { - attributes = new HashMap(); - } - return attributes; - } - - @Override - public Properties getProperties() { - return multiDataSource.getProperties(); - } - - @Override - public DataSourceProxy getDirectDataSource() { - return multiDataSource; - } - - @Override - public Date getConnectedTime() { - return connectedTime; - } - - public boolean isWrapperFor(Class iface) throws SQLException { - boolean result = super.isWrapperFor(iface); - - if ((!result) && conn != null) { - result = conn.isWrapperFor(iface); - } - - return result; - } - - public T unwrap(Class iface) throws SQLException { - T object = super.unwrap(iface); - - if (object == null && conn != null) { - object = conn.unwrap(iface); - } - - return object; - } - - public void setSchema(String schema) throws SQLException { - throw new SQLFeatureNotSupportedException(); - } - - public String getSchema() throws SQLException { - throw new SQLFeatureNotSupportedException(); - } - - public void abort(Executor executor) throws SQLException { - if (conn == null) { - throw new SQLException("connection not init"); - } - - throw new SQLFeatureNotSupportedException(); - } - - public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { - throw new SQLFeatureNotSupportedException(); - } - - public int getNetworkTimeout() throws SQLException { - throw new SQLFeatureNotSupportedException(); - } - - @Override - public TransactionInfo getTransactionInfo() { - return null; - } - - @Override - public int getCloseCount() { - return closeCount; - } - -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourceMBean.java b/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourceMBean.java deleted file mode 100644 index d594b0d0d5..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourceMBean.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha; - - -public interface MultiDataSourceMBean { - long getActiveCount(); -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourcePreparedStatement.java b/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourcePreparedStatement.java deleted file mode 100644 index 34efeefb9a..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourcePreparedStatement.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -import com.alibaba.druid.filter.FilterChain; -import com.alibaba.druid.proxy.jdbc.PreparedStatementProxyImpl; - - -public class MultiDataSourcePreparedStatement extends PreparedStatementProxyImpl { - private MultiDataSourceConnection multiConnection; - - public MultiDataSourcePreparedStatement(MultiDataSourceConnection connection, PreparedStatement statement, String sql, long id){ - super(connection, statement, sql, id); - - multiConnection = connection; - } - - public MultiDataSourceConnection getConnection() { - return multiConnection; - } - - @Override - public boolean execute() throws SQLException { - FilterChain chain = createChain(); - - if (chain.getFilterSize() == 0) { - firstResultSet = this.statement.execute(); - } else { - firstResultSet = chain.preparedStatement_execute(this); - } - - return firstResultSet; - } - - @Override - public ResultSet executeQuery() throws SQLException { - FilterChain chain = createChain(); - - if (chain.getFilterSize() == 0) { - return this.statement.executeQuery(); - } - - return chain.preparedStatement_executeQuery(this); - } - - @Override - public int executeUpdate() throws SQLException { - FilterChain chain = createChain(); - - if (chain.getFilterSize() == 0) { - return this.statement.executeUpdate(); - } - - return chain.preparedStatement_executeUpdate(this); - } -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourceStatManager.java b/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourceStatManager.java deleted file mode 100644 index ce792c6285..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourceStatManager.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha; - -import java.lang.management.ManagementFactory; -import java.util.Set; -import java.util.concurrent.atomic.AtomicLong; - -import javax.management.JMException; -import javax.management.MBeanServer; -import javax.management.ObjectName; - -import com.alibaba.druid.support.logging.Log; -import com.alibaba.druid.support.logging.LogFactory; -import com.alibaba.druid.util.ConcurrentIdentityHashMap; - -public class MultiDataSourceStatManager implements MultiDataSourceStatManagerMBean { - - private final static Log LOG = LogFactory.getLog(MultiDataSourceStatManager.class); - - private final static MultiDataSourceStatManager instance = new MultiDataSourceStatManager(); - - private final AtomicLong resetCount = new AtomicLong(); - - // global instances - private static final ConcurrentIdentityHashMap dataSources = new ConcurrentIdentityHashMap(); - - private final static String MBEAN_NAME = "com.alibaba.druid.ha:type=HADruidDataSourceStat"; - - public static MultiDataSourceStatManager getInstance() { - return instance; - } - - public synchronized static void add(MultiDataSource dataSource) { - MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); - if (dataSources.size() == 0) { - try { - mbeanServer.registerMBean(instance, new ObjectName(MBEAN_NAME)); - } catch (JMException ex) { - LOG.error("register mbean error", ex); - } - } - - ObjectName objectName = null; - if (dataSource.getNameInternal() != null) { - try { - objectName = new ObjectName("com.alibaba.druid.ha:type=DruidDataSource,id=" + dataSource.getNameInternal()); - mbeanServer.registerMBean(dataSource, objectName); - } catch (JMException ex) { - LOG.error("register mbean error", ex); - objectName = null; - } - } - - if (objectName == null) { - try { - int id = System.identityHashCode(dataSource); - objectName = new ObjectName("com.alibaba.druid.ha:type=DruidDataSource,id=" + id); - mbeanServer.registerMBean(dataSource, objectName); - } catch (JMException ex) { - LOG.error("register mbean error", ex); - objectName = null; - } - } - - dataSources.put(dataSource, objectName); - dataSource.setObjectName(objectName); - } - - public synchronized static void remove(MultiDataSource dataSource) { - ObjectName objectName = dataSources.remove(dataSource); - - if (objectName == null) { - objectName = dataSource.getObjectName(); - } - - if (objectName == null) { - LOG.error("unregister mbean failed. "); - return; - } - - MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); - - if (objectName != null) { - try { - mbeanServer.unregisterMBean(objectName); - } catch (JMException ex) { - LOG.error("unregister mbean error", ex); - } - } - - if (dataSources.size() == 0) { - try { - mbeanServer.unregisterMBean(new ObjectName(MBEAN_NAME)); - } catch (JMException ex) { - LOG.error("unregister mbean error", ex); - } - } - } - - public static Set getDruidDataSourceInstances() { - return dataSources.keySet(); - } - - public void reset() { - final Set dataSources = getDruidDataSourceInstances(); - for (MultiDataSource dataSource : dataSources) { - dataSource.resetStat(); - } - - resetCount.incrementAndGet(); - } - - public long getResetCount() { - return resetCount.get(); - } - - -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourceStatManagerMBean.java b/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourceStatManagerMBean.java deleted file mode 100644 index 7af02279af..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourceStatManagerMBean.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha; - - -public interface MultiDataSourceStatManagerMBean { - -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourceStatement.java b/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourceStatement.java deleted file mode 100644 index 2de246356a..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/MultiDataSourceStatement.java +++ /dev/null @@ -1,476 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; -import java.sql.SQLWarning; -import java.sql.Statement; - -import com.alibaba.druid.pool.WrapperAdapter; - -public class MultiDataSourceStatement extends WrapperAdapter implements Statement { - - private final MultiDataSourceConnection conn; - private final long id; - private Integer resultSetType; - private Integer resultSetConcurrency; - private Integer resultSetHoldability; - private Statement stmt; - - private Integer maxFieldSize; - private Integer maxRows; - private Boolean escapeProcessing; - private Integer queryTimeout; - private String cursorName; - private Integer fetchDirection; - private Integer fetchSize; - - void checkStatement(String sql) throws SQLException { - conn.checkConnection(sql); - - if (resultSetType != null && resultSetConcurrency != null && resultSetHoldability != null) { - stmt = conn.getRawObject().createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); - } else if (resultSetType != null && resultSetConcurrency != null) { - stmt = conn.getRawObject().createStatement(resultSetType, resultSetConcurrency); - } else { - stmt = conn.getRawObject().createStatement(); - } - - if (maxFieldSize != null) { - stmt.setMaxFieldSize(maxFieldSize); - } - if (maxRows != null) { - stmt.setMaxRows(maxRows); - } - if (escapeProcessing != null) { - stmt.setEscapeProcessing(escapeProcessing); - } - if (queryTimeout != null) { - stmt.setQueryTimeout(queryTimeout); - } - if (cursorName != null) { - stmt.setCursorName(cursorName); - } - if (fetchDirection != null) { - stmt.setFetchDirection(fetchDirection); - } - if (fetchSize != null) { - stmt.setFetchSize(fetchSize); - } - } - - public MultiDataSourceStatement(MultiDataSourceConnection conn, long id){ - super(); - this.conn = conn; - this.id = id; - } - - public MultiDataSourceStatement(MultiDataSourceConnection conn, long id, int resultSetType, int resultSetConcurrency){ - super(); - this.conn = conn; - this.id = id; - this.resultSetType = resultSetType; - this.resultSetConcurrency = resultSetConcurrency; - } - - public MultiDataSourceStatement(MultiDataSourceConnection conn, long id, int resultSetType, - int resultSetConcurrency, int resultSetHoldability){ - super(); - this.conn = conn; - this.id = id; - this.resultSetType = resultSetType; - this.resultSetConcurrency = resultSetConcurrency; - this.resultSetHoldability = resultSetHoldability; - } - - public long getId() { - return id; - } - - @Override - public ResultSet executeQuery(String sql) throws SQLException { - checkStatement(sql); - - return stmt.executeQuery(sql); - } - - @Override - public int executeUpdate(String sql) throws SQLException { - checkStatement(sql); - return stmt.executeUpdate(sql); - } - - @Override - public void close() throws SQLException { - if (stmt != null) { - stmt.close(); - } - } - - @Override - public int getMaxFieldSize() throws SQLException { - if (stmt != null) { - return stmt.getMaxFieldSize(); - } - - if (maxFieldSize == null) { - return 0; - } - - return maxFieldSize; - } - - @Override - public void setMaxFieldSize(int max) throws SQLException { - if (stmt != null) { - stmt.setMaxFieldSize(max); - return; - } - - this.maxFieldSize = max; - } - - @Override - public int getMaxRows() throws SQLException { - if (stmt != null) { - return stmt.getMaxRows(); - } - - if (maxRows == null) { - return 0; - } - - return maxRows; - } - - @Override - public void setMaxRows(int max) throws SQLException { - if (stmt != null) { - stmt.setMaxRows(max); - return; - } - - this.maxRows = max; - } - - @Override - public void setEscapeProcessing(boolean enable) throws SQLException { - if (stmt != null) { - stmt.setEscapeProcessing(enable); - return; - } - - this.escapeProcessing = enable; - } - - @Override - public int getQueryTimeout() throws SQLException { - if (stmt != null) { - return stmt.getQueryTimeout(); - } - - if (queryTimeout == null) { - return 0; - } - - return queryTimeout; - } - - @Override - public void setQueryTimeout(int seconds) throws SQLException { - if (stmt != null) { - stmt.setQueryTimeout(seconds); - return; - } - - this.queryTimeout = seconds; - } - - @Override - public void cancel() throws SQLException { - if (stmt != null) { - stmt.cancel(); - } - } - - @Override - public SQLWarning getWarnings() throws SQLException { - if (stmt != null) { - return stmt.getWarnings(); - } - - return null; - } - - @Override - public void clearWarnings() throws SQLException { - if (stmt != null) { - stmt.clearWarnings(); - } - } - - @Override - public void setCursorName(String name) throws SQLException { - if (stmt != null) { - stmt.setCursorName(name); - return; - } - - this.cursorName = name; - } - - @Override - public boolean execute(String sql) throws SQLException { - checkStatement(sql); - return stmt.execute(sql); - } - - @Override - public ResultSet getResultSet() throws SQLException { - if (stmt != null) { - return stmt.getResultSet(); - } - - return null; - } - - @Override - public int getUpdateCount() throws SQLException { - if (stmt != null) { - return stmt.getUpdateCount(); - } - - return 0; - } - - @Override - public boolean getMoreResults() throws SQLException { - if (stmt != null) { - return stmt.getMoreResults(); - } - - return false; - } - - @Override - public void setFetchDirection(int direction) throws SQLException { - if (stmt != null) { - stmt.setFetchDirection(direction); - return; - } - - this.fetchDirection = direction; - } - - @Override - public int getFetchDirection() throws SQLException { - if (stmt != null) { - return stmt.getFetchDirection(); - } - - return this.fetchDirection; - } - - @Override - public void setFetchSize(int rows) throws SQLException { - if (stmt != null) { - stmt.setFetchSize(rows); - return; - } - - this.fetchSize = rows; - } - - @Override - public int getFetchSize() throws SQLException { - if (stmt != null) { - return stmt.getFetchSize(); - } - - return this.fetchSize; - } - - @Override - public int getResultSetConcurrency() throws SQLException { - if (stmt != null) { - return stmt.getResultSetConcurrency(); - } - - if (resultSetConcurrency != null) { - return resultSetConcurrency; - } - - return 0; - } - - @Override - public int getResultSetType() throws SQLException { - if (stmt != null) { - return stmt.getResultSetType(); - } - - return resultSetType; - } - - @Override - public void addBatch(String sql) throws SQLException { - checkStatement(sql); - - stmt.addBatch(sql); - } - - @Override - public void clearBatch() throws SQLException { - if (stmt != null) { - stmt.clearBatch(); - } - } - - @Override - public int[] executeBatch() throws SQLException { - if (stmt != null) { - return stmt.executeBatch(); - } - return new int[0]; - } - - @Override - public MultiDataSourceConnection getConnection() throws SQLException { - return conn; - } - - @Override - public boolean getMoreResults(int current) throws SQLException { - if (stmt != null) { - return stmt.getMoreResults(current); - } - - return false; - } - - @Override - public ResultSet getGeneratedKeys() throws SQLException { - if (stmt != null) { - return stmt.getGeneratedKeys(); - } - - return null; - } - - @Override - public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { - checkStatement(sql); - - return stmt.executeUpdate(sql, autoGeneratedKeys); - } - - @Override - public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { - checkStatement(sql); - return stmt.executeUpdate(sql, columnIndexes); - } - - @Override - public int executeUpdate(String sql, String[] columnNames) throws SQLException { - checkStatement(sql); - return stmt.executeUpdate(sql, columnNames); - } - - @Override - public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { - checkStatement(sql); - return stmt.execute(sql, autoGeneratedKeys); - } - - @Override - public boolean execute(String sql, int[] columnIndexes) throws SQLException { - checkStatement(sql); - return stmt.execute(sql, columnIndexes); - } - - @Override - public boolean execute(String sql, String[] columnNames) throws SQLException { - checkStatement(sql); - return stmt.execute(sql, columnNames); - } - - @Override - public int getResultSetHoldability() throws SQLException { - if (stmt != null) { - return stmt.getResultSetHoldability(); - } - - if (resultSetHoldability != null) { - return resultSetHoldability; - } - - return 0; - } - - @Override - public boolean isClosed() throws SQLException { - if (stmt != null) { - return stmt.isClosed(); - } - return false; - } - - @Override - public void setPoolable(boolean poolable) throws SQLException { - throw new SQLException("not supported"); - } - - @Override - public boolean isPoolable() throws SQLException { - return false; - } - - @SuppressWarnings("unchecked") - @Override - public T unwrap(Class iface) throws SQLException { - if (iface == null) { - return null; - } - - if (iface.isInstance(this)) { - return (T) this; - } - - if (stmt != null) { - return stmt.unwrap(iface); - } - - return null; - } - - public Boolean isEscapeProcessing() { - return escapeProcessing; - } - - public String getCursorName() { - return cursorName; - } - - public void closeOnCompletion() throws SQLException { - throw new SQLFeatureNotSupportedException(); - } - - public boolean isCloseOnCompletion() throws SQLException { - throw new SQLFeatureNotSupportedException(); - } -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/balance/AbstractBalancer.java b/src/main/java/com/alibaba/druid/pool/ha/balance/AbstractBalancer.java deleted file mode 100644 index e88e44e8d5..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/balance/AbstractBalancer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha.balance; - -import com.alibaba.druid.pool.ha.MultiDataSource; - -public abstract class AbstractBalancer implements Balancer { - - private MultiDataSource multiDataSource; - - private boolean inited = false; - - @Override - public synchronized void init(MultiDataSource multiDataSource) { - if (this.inited) { - return; - } - - if (multiDataSource == null) { - throw new IllegalStateException(); - } - - this.multiDataSource = multiDataSource; - - inited = true; - } - - public boolean isInited() { - return inited; - } - - public MultiDataSource getMultiDataSource() { - return multiDataSource; - } - -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/balance/Balancer.java b/src/main/java/com/alibaba/druid/pool/ha/balance/Balancer.java deleted file mode 100644 index f1355c6e34..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/balance/Balancer.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha.balance; - -import java.sql.SQLException; - -import com.alibaba.druid.pool.ha.DataSourceChangedEvent; -import com.alibaba.druid.pool.ha.MultiConnectionHolder; -import com.alibaba.druid.pool.ha.MultiDataSource; -import com.alibaba.druid.pool.ha.MultiDataSourceConnection; - -public interface Balancer { - - boolean isInited(); - - void init(MultiDataSource dataSource); - - void afterDataSourceChanged(DataSourceChangedEvent event); - - MultiConnectionHolder getConnection(MultiDataSourceConnection connectionProxy, String sql) throws SQLException; -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/balance/LeastConnectionBalancer.java b/src/main/java/com/alibaba/druid/pool/ha/balance/LeastConnectionBalancer.java deleted file mode 100644 index cd7fc18a8c..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/balance/LeastConnectionBalancer.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha.balance; - -import java.sql.SQLException; - -import com.alibaba.druid.pool.ha.DataSourceChangedEvent; -import com.alibaba.druid.pool.ha.DataSourceHolder; -import com.alibaba.druid.pool.ha.MultiConnectionHolder; -import com.alibaba.druid.pool.ha.MultiDataSource; -import com.alibaba.druid.pool.ha.MultiDataSourceConnection; - -public class LeastConnectionBalancer extends AbstractBalancer { - - @Override - public void afterDataSourceChanged(DataSourceChangedEvent event) { - - } - - @Override - public MultiConnectionHolder getConnection(MultiDataSourceConnection conn, String sql) throws SQLException { - MultiDataSource multiDataSource = conn.getMultiDataSource(); - - DataSourceHolder dataSource = null; - int leastCount = -1; - - for (DataSourceHolder item : multiDataSource.getDataSources().values()) { - if (!item.isEnable()) { - continue; - } - - int activeCount = item.getDataSource().getActiveCount(); - if (dataSource == null) { - leastCount = activeCount; - dataSource = item; - } else { - if (leastCount > item.getDataSource().getActiveCount()) { - dataSource = item; - leastCount = activeCount; - } - } - } - - if (dataSource == null) { - throw new SQLException("can not get real connection, enableDataSourceCount " - + multiDataSource.getEnabledDataSourceCount()); - } - - return dataSource.getConnection(); - } - -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/balance/RoundRobinBlancer.java b/src/main/java/com/alibaba/druid/pool/ha/balance/RoundRobinBlancer.java deleted file mode 100644 index 08a98b620d..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/balance/RoundRobinBlancer.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha.balance; - -import java.sql.SQLException; -import java.util.concurrent.atomic.AtomicInteger; - -import com.alibaba.druid.pool.ha.DataSourceChangedEvent; -import com.alibaba.druid.pool.ha.DataSourceHolder; -import com.alibaba.druid.pool.ha.MultiConnectionHolder; -import com.alibaba.druid.pool.ha.MultiDataSource; -import com.alibaba.druid.pool.ha.MultiDataSourceConnection; -import com.alibaba.druid.support.logging.Log; -import com.alibaba.druid.support.logging.LogFactory; - -public class RoundRobinBlancer extends AbstractBalancer { - - private final static Log LOG = LogFactory.getLog(RoundRobinBlancer.class); - - private final AtomicInteger indexErrorCount = new AtomicInteger(); - - public RoundRobinBlancer(){ - - } - - public void afterDataSourceChanged(DataSourceChangedEvent event) { - - } - - @Override - public MultiConnectionHolder getConnection(MultiDataSourceConnection conn, String sql) throws SQLException { - MultiDataSource multiDataSource = conn.getMultiDataSource(); - - int size = multiDataSource.getDataSources().size(); - long connectionId = (int) conn.getId(); - - if (size == 0) { - throw new SQLException("can not get connection, no availabe datasources"); - } - - int index = (int) (connectionId % size); - - DataSourceHolder first = null; - DataSourceHolder dataSource = null; - - try { - int itemIndex = 0; - for (DataSourceHolder item : multiDataSource.getDataSources().values()) { - if (!item.isEnable()) { - continue; - } - - if (first == null) { - first = item; - } - - if (itemIndex == index) { - dataSource = item; - break; - } - itemIndex++; - } - - if (dataSource == null) { - dataSource = first; - } - } catch (Exception ex) { - indexErrorCount.incrementAndGet(); - if (LOG.isDebugEnabled()) { - LOG.debug("getDataSource error, index : " + index, ex); - } - } - - if (dataSource == null) { - throw new SQLException("can not get real connection."); - } - - MultiConnectionHolder holder = null; - - return holder; - } - - public long getIndexErrorCount() { - return indexErrorCount.get(); - } -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/balance/WeightBalancer.java b/src/main/java/com/alibaba/druid/pool/ha/balance/WeightBalancer.java deleted file mode 100644 index f3caf3b001..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/balance/WeightBalancer.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha.balance; - -import java.sql.SQLException; - -import com.alibaba.druid.pool.ha.DataSourceChangedEvent; -import com.alibaba.druid.pool.ha.DataSourceHolder; -import com.alibaba.druid.pool.ha.MultiConnectionHolder; -import com.alibaba.druid.pool.ha.MultiDataSource; -import com.alibaba.druid.pool.ha.MultiDataSourceConnection; -import com.alibaba.druid.util.ThreadLocalRandom; - -public class WeightBalancer extends AbstractBalancer { - - private int totalWeight = 0; - - public void afterDataSourceChanged(DataSourceChangedEvent event) { - computeTotalWeight(); - } - - public int produceRandomNumber() { - if (totalWeight == 0) { - return 0; - } - - return ThreadLocalRandom.current().nextInt(totalWeight); - } - - public void computeTotalWeight() { - int totalWeight = 0; - for (DataSourceHolder holder : getMultiDataSource().getDataSources().values()) { - if (!holder.isEnable()) { - holder.setWeightRegionBegin(-1); - holder.setWeightRegionEnd(-1); - continue; - } - holder.setWeightRegionBegin(totalWeight); - totalWeight += holder.getWeight(); - holder.setWeightRegionEnd(totalWeight); - } - this.totalWeight = totalWeight; - - getMultiDataSource().notFailSignal(); - } - - @Override - public MultiConnectionHolder getConnection(MultiDataSourceConnection conn, String sql) throws SQLException { - MultiDataSource multiDataSource = conn.getMultiDataSource(); - - DataSourceHolder dataSource = null; - - int randomNumber = produceRandomNumber(); - DataSourceHolder first = null; - - for (DataSourceHolder item : multiDataSource.getDataSources().values()) { - if (!item.isEnable()) { - continue; - } - - if (first == null) { - first = item; - } - - if (randomNumber >= item.getWeightRegionBegin() && randomNumber < item.getWeightRegionEnd()) { - if (!item.isEnable()) { - continue; - } - - if (item.getDataSource().isBusy()) { - multiDataSource.incrementBusySkipCount(); - break; - } - - dataSource = item; - } - } - - if (dataSource == null) { - dataSource = first; - } - - if (dataSource == null) { - throw new SQLException("cannot get connection. enabledDataSourceCount " - + multiDataSource.getEnabledDataSourceCount()); - } - - return dataSource.getConnection(); - } - -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/cobar/CobarConfigLoader.java b/src/main/java/com/alibaba/druid/pool/ha/cobar/CobarConfigLoader.java deleted file mode 100644 index acdf162954..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/cobar/CobarConfigLoader.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha.cobar; - -import java.net.MalformedURLException; -import java.net.URL; -import java.sql.SQLException; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.alibaba.druid.pool.ha.DataSourceHolder; -import com.alibaba.druid.pool.ha.config.ConfigLoader; -import com.alibaba.druid.pool.ha.config.URLConnectionConfigLoader; -import com.alibaba.druid.support.json.JSONUtils; - -public class CobarConfigLoader extends URLConnectionConfigLoader implements ConfigLoader { - - private final CobarDataSource dataSource; - - public CobarConfigLoader(CobarDataSource cobarDataSource) throws SQLException{ - super(createURL(cobarDataSource.getUrl())); - - this.dataSource = cobarDataSource; - } - - public CobarDataSource getDataSource() { - return dataSource; - } - - public static boolean isCobar(String url) { - return url.startsWith("jdbc:cobar://"); - } - - public static URL createURL(String jdbcUrl) throws SQLException { - if (!isCobar(jdbcUrl)) { - throw new SQLException("illegal cobar url"); - } - - // jdbc:cobar://ip:port/sid - String rest = jdbcUrl.substring("jdbc:cobar://".length()); - String[] items = rest.split("/"); - String ip = items[0]; - String sid = items[1]; - - int port = 80; - { - int pos = ip.indexOf(':'); - if (pos != -1) { - port = Integer.parseInt(ip.substring(pos + 1)); - ip = ip.substring(0, pos); - } - } - - //String url = "http://" + ip + ":" + port + "/cobarStatusQuery?sid=" + sid; - String url = "http://" + ip + ":" + port + "/cobarStatusQuery?sid=" + sid; - - try { - return new URL(url); - } catch (MalformedURLException e) { - throw new SQLException(e.getMessage(), e); - } - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - protected void handleResponseMessage() throws SQLException { - String responseMessage = this.getResponseMessage(); - - Map json = (Map) JSONUtils.parse(responseMessage); - String errorMessage = (String) json.get("error"); - if (errorMessage != null) { - throw new SQLException("load config error, message : " + errorMessage); - } - - List array = (List) json.get("cobarList"); - - Set keys = new HashSet(); - for (int i = 0; i < array.size(); ++i) { - Map item = (Map) array.get(i); - - String ip = (String) item.get("ip"); - int port = (Integer) item.get("port"); - String schema = (String) item.get("schema"); - int weight = (Integer) item.get("weight"); - - String key = ip + ":" + port + "/" + schema; - keys.add(key); - - DataSourceHolder holder = dataSource.getDataSourceHolder(key); - - if (holder == null) { - String jdbcUrl = createJdbcUrl(ip, port, schema); - holder = dataSource.createDataSourceHolder(jdbcUrl, weight); - dataSource.addDataSource(key, holder); - } else { - if (holder.getWeight() != weight) { - holder.setWeight(weight); - dataSource.afterDataSourceChanged(null); - } - } - } - - int removeCount = 0; - Iterator> iter = dataSource.getDataSources().entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = iter.next(); - if (!keys.contains(entry.getKey())) { - iter.remove(); - dataSource.handleDataSourceDiscard(entry.getValue()); - removeCount++; - } - } - if (removeCount != 0) { - dataSource.afterDataSourceChanged(null); - } - } - - protected String createJdbcUrl(String ip, int port, String schema) { - return "jdbc:mysql://" + ip + ":" + port + "/" + schema; - } - -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/cobar/CobarDataSource.java b/src/main/java/com/alibaba/druid/pool/ha/cobar/CobarDataSource.java deleted file mode 100644 index cb83ae2738..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/cobar/CobarDataSource.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha.cobar; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import com.alibaba.druid.filter.Filter; -import com.alibaba.druid.pool.DruidDataSource; -import com.alibaba.druid.pool.ha.DataSourceHolder; -import com.alibaba.druid.pool.ha.MultiDataSource; -import com.alibaba.druid.support.logging.Log; -import com.alibaba.druid.support.logging.LogFactory; -import com.alibaba.druid.util.JdbcUtils; - -public class CobarDataSource extends MultiDataSource { - - private final static Log LOG = LogFactory.getLog(CobarDataSource.class); - - public final static long DEFAULT_FAILURE_DETECT_PERRIOD_MILLIS = 1000 * 3; // 3 - // seconds - public final static long DEFAULT_CONFIG_LOAD_PERRIOD_MILLIS = 1000 * 60 * 3; // 3 - // minutes - - private String url; - - private String username; - - private String password; - - private long minEvictableIdleTimeMillis = 1000 * 60 * 3; // 3 - // minutes - - private boolean testWhileIdle = true; - - private List proxyFilters = new ArrayList(); - private String filters; - - public CobarDataSource(){ - this.setFailureDetector(new CobarFailureDetecter()); - this.setFailureDetectPeriodMillis(DEFAULT_FAILURE_DETECT_PERRIOD_MILLIS); - this.setConfigLoadPeriodMillis(DEFAULT_CONFIG_LOAD_PERRIOD_MILLIS); - } - - public boolean isTestWhileIdle() { - return testWhileIdle; - } - - public void setTestWhileIdle(boolean testWhileIdle) { - this.testWhileIdle = testWhileIdle; - } - - public long getMinEvictableIdleTimeMillis() { - return minEvictableIdleTimeMillis; - } - - public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { - this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public List getProxyFilters() { - return proxyFilters; - } - - public void setProxyFilters(List proxyFilters) { - this.proxyFilters = proxyFilters; - } - - public String getFilters() { - return filters; - } - - public void setFilters(String filters) { - this.filters = filters; - } - - protected void initInternal() throws SQLException { - if (url == null || url.isEmpty()) { - throw new SQLException(""); - } - - if (CobarConfigLoader.isCobar(url)) { - if (this.getConfigLoader() == null) { - this.setConfigLoader(new CobarConfigLoader(this)); - } - - final int RETRY_COUNT = 3; - for (int i = 0; i < RETRY_COUNT; ++i) { - try { - this.getConfigLoader().load(); - break; - } catch (Exception ex) { - LOG.error("load config error", ex); - - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - return; - } - } - } - } else { - DataSourceHolder holder = createDataSourceHolder(this.url, 1); - this.addDataSource("master", holder); - } - } - - protected DataSourceHolder createDataSourceHolder(String url, int weight) throws SQLException { - DruidDataSource dataSource = new DruidDataSource(); - dataSource.setUrl(url); - dataSource.setUsername(username); - dataSource.setPassword(password); - dataSource.setMaxActive(getMaxPoolSize()); - dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); // 3 minutes - dataSource.setTestWhileIdle(testWhileIdle); - - if (filters != null && !filters.isEmpty()) { - dataSource.setFilters(filters); - } - dataSource.setProxyFilters(proxyFilters); - - DataSourceHolder holder = new DataSourceHolder(this, dataSource); - holder.setWeight(weight); - return holder; - } - - protected void handleDataSourceDiscard(DataSourceHolder holder) { - LOG.debug("dataSource close"); - JdbcUtils.close(holder); - } - -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/cobar/CobarFailureDetecter.java b/src/main/java/com/alibaba/druid/pool/ha/cobar/CobarFailureDetecter.java deleted file mode 100644 index fd620dbc20..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/cobar/CobarFailureDetecter.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha.cobar; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.Statement; - -import com.alibaba.druid.pool.DruidDataSource; -import com.alibaba.druid.pool.ha.valid.DefaultDataSourceFailureDetecter; -import com.alibaba.druid.support.logging.Log; -import com.alibaba.druid.support.logging.LogFactory; -import com.alibaba.druid.util.JdbcUtils; - -public class CobarFailureDetecter extends DefaultDataSourceFailureDetecter { - - private final static Log LOG = LogFactory.getLog(CobarFailureDetecter.class); - - private int queryTimeoutSeconds = 30; - - public CobarFailureDetecter(){ - this.setValidateSql("SHOW COBAR_STATUS"); - } - - public int getQueryTimeoutSeconds() { - return queryTimeoutSeconds; - } - - public void setQueryTimeoutSeconds(int queryTimeoutSeconds) { - this.queryTimeoutSeconds = queryTimeoutSeconds; - } - - public boolean isValidConnection(DruidDataSource dataSource, Connection conn) { - Statement stmt = null; - ResultSet rs = null; - try { - stmt = conn.createStatement(); - stmt.setQueryTimeout(queryTimeoutSeconds); - rs = stmt.executeQuery(getValidateSql()); - if (!rs.next()) { - return false; - } - - String status = rs.getString(1); - - return "on".equalsIgnoreCase(status); - } catch (Exception ex) { - LOG.error("check datasource valid errror", ex); - return false; - } finally { - JdbcUtils.close(rs); - JdbcUtils.close(stmt); - } - - } -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/config/ConfigLoader.java b/src/main/java/com/alibaba/druid/pool/ha/config/ConfigLoader.java deleted file mode 100644 index 15dcadbb96..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/config/ConfigLoader.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha.config; - -import java.sql.SQLException; - -public interface ConfigLoader { - void load() throws SQLException; -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/config/HAConfigLoader.java b/src/main/java/com/alibaba/druid/pool/ha/config/HAConfigLoader.java deleted file mode 100644 index 96b3c88399..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/config/HAConfigLoader.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha.config; - -import java.net.URL; -import java.sql.SQLException; -import java.util.Map; - -import com.alibaba.druid.support.json.JSONUtils; - -public class HAConfigLoader extends URLConnectionConfigLoader { - - public HAConfigLoader(URL configServerURL){ - super(configServerURL); - } - - @Override - protected void handleResponseMessage() throws SQLException { - @SuppressWarnings("unchecked") - Map map = (Map) JSONUtils.parse(this.getResponseMessage()); - map.get("serverList"); - } - -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/config/URLConnectionConfigLoader.java b/src/main/java/com/alibaba/druid/pool/ha/config/URLConnectionConfigLoader.java deleted file mode 100644 index 6635fedbae..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/config/URLConnectionConfigLoader.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha.config; - -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.sql.SQLException; - -import com.alibaba.druid.util.IOUtils; -import com.alibaba.druid.util.JdbcUtils; - -public abstract class URLConnectionConfigLoader implements ConfigLoader { - - private URL url; - private int connectTimeout = 1000 * 3; - private int readTimeout; - - protected String responseMessage; - - public URLConnectionConfigLoader(URL configServerURL){ - this.url = configServerURL; - } - - public URLConnectionConfigLoader(String url) throws MalformedURLException{ - this.url = new URL(url); - } - - public URL getURL() { - return url; - } - - public void setURL(URL url) { - this.url = url; - } - - public int getConnectTimeout() { - return connectTimeout; - } - - public void setConnectTimeout(int connectTimeout) { - this.connectTimeout = connectTimeout; - } - - public int getReadTimeout() { - return readTimeout; - } - - public void setReadTimeout(int readTimeout) { - this.readTimeout = readTimeout; - } - - public String getResponseMessage() { - return responseMessage; - } - - @Override - public void load() throws SQLException { - if (url == null) { - throw new IllegalStateException("configServerURL is null"); - } - - { - HttpURLConnection conn = null; - Reader reader = null; - try { - conn = (HttpURLConnection) url.openConnection(); - - conn.setConnectTimeout(connectTimeout); - conn.setReadTimeout(readTimeout); - - conn.connect(); - - reader = new InputStreamReader(conn.getInputStream()); - responseMessage = IOUtils.read(reader); - - handleResponseMessage(); - } catch (Exception e) { - throw new SQLException("load config error, url : " + url.toString(), e); - } finally { - JdbcUtils.close(reader); - conn.disconnect(); - } - } - } - - protected abstract void handleResponseMessage() throws SQLException; - -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/valid/DataSourceFailureDetecter.java b/src/main/java/com/alibaba/druid/pool/ha/valid/DataSourceFailureDetecter.java deleted file mode 100644 index 130f593f98..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/valid/DataSourceFailureDetecter.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha.valid; - -import com.alibaba.druid.pool.DruidDataSource; - - -public interface DataSourceFailureDetecter { - boolean isValid(DruidDataSource dataSource); -} diff --git a/src/main/java/com/alibaba/druid/pool/ha/valid/DefaultDataSourceFailureDetecter.java b/src/main/java/com/alibaba/druid/pool/ha/valid/DefaultDataSourceFailureDetecter.java deleted file mode 100644 index d6949b8edb..0000000000 --- a/src/main/java/com/alibaba/druid/pool/ha/valid/DefaultDataSourceFailureDetecter.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha.valid; - -import java.sql.Connection; -import java.sql.Statement; - -import com.alibaba.druid.pool.DruidDataSource; -import com.alibaba.druid.support.logging.Log; -import com.alibaba.druid.support.logging.LogFactory; -import com.alibaba.druid.util.JdbcUtils; - -public class DefaultDataSourceFailureDetecter implements DataSourceFailureDetecter { - - private final static Log LOG = LogFactory.getLog(DefaultDataSourceFailureDetecter.class); - - private long maxWaitMillis = 3000; - - private String validateSql = "SELECT 1"; - - public long getMaxWaitMillis() { - return maxWaitMillis; - } - - public void setMaxWaitMillis(long maxWaitMillis) { - this.maxWaitMillis = maxWaitMillis; - } - - public String getValidateSql() { - return validateSql; - } - - public void setValidateSql(String validateSql) { - this.validateSql = validateSql; - } - - @Override - public boolean isValid(DruidDataSource dataSource) { - Connection conn = null; - - try { - conn = dataSource.getConnection(maxWaitMillis); - - if (conn == null) { - return false; - } - - return isValidConnection(dataSource, conn); - - } catch (Exception ex) { - LOG.error("check datasource valid errror", ex); - } finally { - JdbcUtils.close(conn); - } - - return false; - } - - public boolean isValidConnection(DruidDataSource dataSource, Connection conn) { - Statement stmt = null; - - try { - stmt = conn.createStatement(); - stmt.execute(getValidateSql()); - } catch (Exception ex) { - LOG.error("check datasource valid errror", ex); - } finally { - JdbcUtils.close(stmt); - } - - return true; - } - -} diff --git a/src/test/java/com/alibaba/druid/bvt/pool/ha/CobarDataSourceTest.java b/src/test/java/com/alibaba/druid/bvt/pool/ha/CobarDataSourceTest.java deleted file mode 100644 index 5a11a058de..0000000000 --- a/src/test/java/com/alibaba/druid/bvt/pool/ha/CobarDataSourceTest.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.bvt.pool.ha; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.concurrent.atomic.AtomicBoolean; - -import junit.framework.TestCase; - -import org.junit.Assert; - -import com.alibaba.druid.mock.MockConnection; -import com.alibaba.druid.pool.DruidDataSource; -import com.alibaba.druid.pool.ha.cobar.CobarConfigLoader; -import com.alibaba.druid.pool.ha.cobar.CobarDataSource; -import com.alibaba.druid.pool.ha.cobar.CobarFailureDetecter; -import com.alibaba.druid.stat.DruidDataSourceStatManager; -import com.alibaba.druid.support.json.JSONUtils; -import com.alibaba.druid.util.JdbcUtils; - -public class CobarDataSourceTest extends TestCase { - protected void setUp() throws Exception { - for (DruidDataSource item : DruidDataSourceStatManager.getDruidDataSourceInstances()) { - JdbcUtils.close(item); - } - } - - public void test_cobarDataSource() throws Exception { - String url = "jdbc:cobar://127.0.0.1:8080/druid"; - - final HashMap config = new HashMap(); - - ArrayList cobarList = new ArrayList(); - - HashMap cobarA = new HashMap(); - cobarA.put("ip", "mock"); - cobarA.put("port", 80); - cobarA.put("schema", "cobarA"); - cobarA.put("weight", 1); - - cobarList.add(cobarA); - - HashMap cobarB = new HashMap(); - cobarB.put("ip", "mock"); - cobarB.put("port", 81); - cobarB.put("schema", "cobarB"); - cobarB.put("weight", 1); - - cobarList.add(cobarB); - - final String mockUrlA = "jdbc:mock://mock:80/cobarA"; - final String mockUrlB = "jdbc:mock://mock:81/cobarB"; - - final AtomicBoolean statusA = new AtomicBoolean(true); - final AtomicBoolean statusB = new AtomicBoolean(true); - - config.put("cobarList", cobarList); - - final CobarDataSource dataSource = new CobarDataSource(); - dataSource.setUrl(url); - dataSource.setUsername("test"); - dataSource.setPassword(""); - dataSource.setMaxWait(1); - dataSource.setConfigLoadPeriodMillis(10); - dataSource.setFailureDetectPeriodMillis(1); - - CobarConfigLoader configLoader = new CobarConfigLoader(dataSource) { - - public void load() throws SQLException { - responseMessage = JSONUtils.toJSONString(config); - - handleResponseMessage(); - } - - protected String createJdbcUrl(String ip, int port, String schema) { - return "jdbc:mock://" + ip + ":" + port + "/" + schema; - } - }; - dataSource.setConfigLoader(configLoader); - - CobarFailureDetecter failureDetector = new CobarFailureDetecter() { - public boolean isValidConnection(DruidDataSource dataSource, Connection conn) { - MockConnection mockConn; - try { - mockConn = conn.unwrap(MockConnection.class); - } catch (SQLException e) { - e.printStackTrace(); - return false; - } - if (mockConn.getUrl().equals(mockUrlA)) { - return statusA.get(); - } - return statusB.get(); - } - }; - dataSource.setFailureDetector(failureDetector); - - { - Connection conn = dataSource.getConnection(); - Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("select 1"); - rs.next(); - rs.close(); - stmt.close(); - conn.close(); - } - - cobarList.remove(cobarB); - Assert.assertEquals(1, cobarList.size()); - Thread.sleep(dataSource.getConfigLoadPeriodMillis() * 2); - for (int i = 0; i < 100; ++i) { - Connection conn = dataSource.getConnection(); - Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("select 1"); - - MockConnection mockConn = conn.unwrap(MockConnection.class); - Assert.assertNotNull(mockConn); - Assert.assertEquals(mockUrlA, mockConn.getUrl()); - - rs.next(); - rs.close(); - stmt.close(); - conn.close(); - } - - cobarList.add(cobarB); - Assert.assertEquals(2, cobarList.size()); - cobarList.remove(cobarA); - Assert.assertEquals(1, cobarList.size()); - Thread.sleep(dataSource.getConfigLoadPeriodMillis() * 2); - for (int i = 0; i < 100; ++i) { - Connection conn = dataSource.getConnection(); - Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("select 1"); - - MockConnection mockConn = conn.unwrap(MockConnection.class); - Assert.assertNotNull(mockConn); - Assert.assertEquals(mockUrlB, mockConn.getUrl()); - - rs.next(); - rs.close(); - stmt.close(); - conn.close(); - } - - cobarList.add(cobarA); - Assert.assertEquals(2, cobarList.size()); - Thread.sleep(dataSource.getConfigLoadPeriodMillis() * 2); - for (int i = 0; i < 100; ++i) { - Connection conn = dataSource.getConnection(); - Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("select 1"); - - rs.next(); - rs.close(); - stmt.close(); - conn.close(); - } - - statusA.set(false); - Thread.sleep(dataSource.getFailureDetectPeriodMillis() * 2); - for (int i = 0; i < 100; ++i) { - Connection conn = dataSource.getConnection(); - Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("select 1"); - - MockConnection mockConn = conn.unwrap(MockConnection.class); - Assert.assertNotNull(mockConn); - Assert.assertEquals(mockUrlB, mockConn.getUrl()); - - rs.next(); - rs.close(); - stmt.close(); - conn.close(); - } - - statusA.set(true); - statusB.set(false); - Thread.sleep(dataSource.getFailureDetectPeriodMillis() * 2); - for (int i = 0; i < 100; ++i) { - Connection conn = dataSource.getConnection(); - Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("select 1"); - - MockConnection mockConn = conn.unwrap(MockConnection.class); - Assert.assertNotNull(mockConn); - Assert.assertEquals(mockUrlA, mockConn.getUrl()); - - rs.next(); - rs.close(); - stmt.close(); - conn.close(); - } - - dataSource.close(); - } - -} diff --git a/src/test/java/com/alibaba/druid/bvt/pool/ha/HADataSourceTest.java b/src/test/java/com/alibaba/druid/bvt/pool/ha/HADataSourceTest.java deleted file mode 100644 index b8e022eb82..0000000000 --- a/src/test/java/com/alibaba/druid/bvt/pool/ha/HADataSourceTest.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.bvt.pool.ha; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.Statement; - -import junit.framework.Assert; -import junit.framework.TestCase; - -import com.alibaba.druid.mock.MockStatement; -import com.alibaba.druid.pool.DruidDataSource; -import com.alibaba.druid.pool.ha.HADataSource; -import com.alibaba.druid.pool.ha.MultiDataSourceStatement; -import com.alibaba.druid.stat.DruidDataSourceStatManager; -import com.alibaba.druid.util.JdbcUtils; - -public class HADataSourceTest extends TestCase { - - private DruidDataSource dataSourceA; - private DruidDataSource dataSourceB; - - private HADataSource dataSourceHA; - - protected void setUp() throws Exception { - for (DruidDataSource item : DruidDataSourceStatManager.getDruidDataSourceInstances()) { - JdbcUtils.close(item); - } - - Assert.assertEquals(0, DruidDataSourceStatManager.getInstance().getDataSourceList().size()); - - dataSourceA = new DruidDataSource(); - dataSourceA.setUrl("jdbc:mock:ha1"); - dataSourceA.setFilters("trace"); - - dataSourceB = new DruidDataSource(); - dataSourceB.setUrl("jdbc:mock:ha2"); - dataSourceB.setFilters("stat"); - - dataSourceHA = new HADataSource(); - dataSourceHA.setMaster(dataSourceA); - dataSourceHA.setSlave(dataSourceB); - } - - protected void tearDown() throws Exception { - dataSourceHA.close(); - - for (DruidDataSource dataSource : DruidDataSourceStatManager.getDruidDataSourceInstances()) { - dataSource.close(); - } - - Assert.assertEquals(0, DruidDataSourceStatManager.getInstance().getDataSourceList().size()); - } - - public void test_createStatement_0() throws Exception { - Connection conn = dataSourceHA.getConnection(); - - Statement stmt = conn.createStatement(); - - stmt.setMaxFieldSize(100); - stmt.setMaxRows(201); - stmt.setEscapeProcessing(true); - stmt.setQueryTimeout(101); - stmt.setCursorName("cName"); - stmt.setFetchDirection(ResultSet.FETCH_REVERSE); - stmt.setFetchSize(202); - { - MultiDataSourceStatement dsStmt = stmt.unwrap(MultiDataSourceStatement.class); - Assert.assertTrue(dsStmt.getId() > 0); - - Assert.assertEquals(100, stmt.getMaxFieldSize()); - Assert.assertEquals(201, stmt.getMaxRows()); - Assert.assertEquals(true, dsStmt.isEscapeProcessing().booleanValue()); - Assert.assertEquals(101, stmt.getQueryTimeout()); - Assert.assertEquals("cName", dsStmt.getCursorName()); - Assert.assertEquals(ResultSet.FETCH_REVERSE, stmt.getFetchDirection()); - Assert.assertEquals(202, stmt.getFetchSize()); - } - - ResultSet rs = stmt.executeQuery("SELECT 1"); - rs.close(); - - MockStatement mockStmt = stmt.unwrap(MockStatement.class); - Assert.assertEquals(100, mockStmt.getMaxFieldSize()); - Assert.assertEquals(201, mockStmt.getMaxRows()); - Assert.assertEquals(true, mockStmt.isEscapeProcessing()); - Assert.assertEquals(101, mockStmt.getQueryTimeout()); - Assert.assertEquals("cName", mockStmt.getCursorName()); - Assert.assertEquals(ResultSet.FETCH_REVERSE, mockStmt.getFetchDirection()); - Assert.assertEquals(202, mockStmt.getFetchSize()); - - { - MultiDataSourceStatement dsStmt = stmt.unwrap(MultiDataSourceStatement.class); - Assert.assertTrue(dsStmt.getId() > 0); - - Assert.assertEquals(100, stmt.getMaxFieldSize()); - Assert.assertEquals(201, stmt.getMaxRows()); - Assert.assertEquals(true, dsStmt.isEscapeProcessing().booleanValue()); - Assert.assertEquals(101, stmt.getQueryTimeout()); - Assert.assertEquals("cName", dsStmt.getCursorName()); - Assert.assertEquals(ResultSet.FETCH_REVERSE, stmt.getFetchDirection()); - Assert.assertEquals(202, stmt.getFetchSize()); - } - - stmt.close(); - - conn.close(); - } - - public void test_createStatement_1() throws Exception { - Connection conn = dataSourceHA.getConnection(); - - Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); - ResultSet rs = stmt.executeQuery("SELECT 1"); - rs.close(); - - MockStatement mockStmt = stmt.unwrap(MockStatement.class); - Assert.assertEquals(ResultSet.TYPE_SCROLL_INSENSITIVE, mockStmt.getResultSetType()); - Assert.assertEquals(ResultSet.CONCUR_UPDATABLE, mockStmt.getResultSetConcurrency()); - Assert.assertEquals(ResultSet.TYPE_SCROLL_INSENSITIVE, stmt.getResultSetType()); - Assert.assertEquals(ResultSet.CONCUR_UPDATABLE, stmt.getResultSetConcurrency()); - - stmt.close(); - - conn.close(); - } - - public void test_createStatement_2() throws Exception { - Connection conn = dataSourceHA.getConnection(); - - Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE, - ResultSet.CLOSE_CURSORS_AT_COMMIT); - ResultSet rs = stmt.executeQuery("SELECT 1"); - rs.close(); - - MockStatement mockStmt = stmt.unwrap(MockStatement.class); - Assert.assertEquals(ResultSet.TYPE_SCROLL_INSENSITIVE, mockStmt.getResultSetType()); - Assert.assertEquals(ResultSet.CONCUR_UPDATABLE, mockStmt.getResultSetConcurrency()); - Assert.assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, mockStmt.getResultSetHoldability()); - Assert.assertEquals(ResultSet.TYPE_SCROLL_INSENSITIVE, stmt.getResultSetType()); - Assert.assertEquals(ResultSet.CONCUR_UPDATABLE, stmt.getResultSetConcurrency()); - Assert.assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, stmt.getResultSetHoldability()); - - stmt.close(); - - conn.close(); - } - - public void test_createStatement_3() throws Exception { - Connection conn = dataSourceHA.getConnection(); - - Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE, - ResultSet.CLOSE_CURSORS_AT_COMMIT); - ResultSet rs = stmt.executeQuery("SELECT 1"); - rs.close(); - - MockStatement mockStmt = stmt.unwrap(MockStatement.class); - Assert.assertEquals(ResultSet.TYPE_SCROLL_INSENSITIVE, mockStmt.getResultSetType()); - Assert.assertEquals(ResultSet.CONCUR_UPDATABLE, mockStmt.getResultSetConcurrency()); - Assert.assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, mockStmt.getResultSetHoldability()); - Assert.assertEquals(ResultSet.TYPE_SCROLL_INSENSITIVE, stmt.getResultSetType()); - Assert.assertEquals(ResultSet.CONCUR_UPDATABLE, stmt.getResultSetConcurrency()); - Assert.assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, stmt.getResultSetHoldability()); - - stmt.close(); - - conn.close(); - } - - public void test_createStatement_4() throws Exception { - Connection conn = dataSourceHA.getConnection(); - - Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE, - ResultSet.CLOSE_CURSORS_AT_COMMIT); - stmt.executeUpdate("SET @user = 'xxx'"); - - MockStatement mockStmt = stmt.unwrap(MockStatement.class); - Assert.assertEquals(ResultSet.TYPE_SCROLL_INSENSITIVE, mockStmt.getResultSetType()); - Assert.assertEquals(ResultSet.CONCUR_UPDATABLE, mockStmt.getResultSetConcurrency()); - Assert.assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, mockStmt.getResultSetHoldability()); - Assert.assertEquals(ResultSet.TYPE_SCROLL_INSENSITIVE, stmt.getResultSetType()); - Assert.assertEquals(ResultSet.CONCUR_UPDATABLE, stmt.getResultSetConcurrency()); - Assert.assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, stmt.getResultSetHoldability()); - - stmt.close(); - - conn.close(); - } - - public void test_close() throws Exception { - Connection conn = dataSourceHA.getConnection(); - - Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE, - ResultSet.CLOSE_CURSORS_AT_COMMIT); - - stmt.getMaxFieldSize(); - stmt.getMaxRows(); - stmt.cancel(); - stmt.getWarnings(); - stmt.clearWarnings(); - stmt.getResultSet(); - stmt.getUpdateCount(); - stmt.getMoreResults(); - stmt.getMoreResults(1); - stmt.getResultSetConcurrency(); - stmt.getResultSetHoldability(); - stmt.getResultSetType(); - stmt.getConnection(); - stmt.getGeneratedKeys(); - stmt.isClosed(); - stmt.close(); - - conn.close(); - } -} diff --git a/src/test/java/com/alibaba/druid/bvt/pool/ha/HADataSourceTest2.java b/src/test/java/com/alibaba/druid/bvt/pool/ha/HADataSourceTest2.java deleted file mode 100644 index cf863b5122..0000000000 --- a/src/test/java/com/alibaba/druid/bvt/pool/ha/HADataSourceTest2.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.bvt.pool.ha; - -import java.sql.Connection; -import java.sql.Statement; - -import junit.framework.Assert; -import junit.framework.TestCase; - -import com.alibaba.druid.mock.MockConnection; -import com.alibaba.druid.pool.DruidDataSource; -import com.alibaba.druid.pool.ha.HADataSource; -import com.alibaba.druid.stat.DruidDataSourceStatManager; -import com.alibaba.druid.util.JdbcUtils; - -public class HADataSourceTest2 extends TestCase { - - private DruidDataSource dataSourceA; - private DruidDataSource dataSourceB; - - private HADataSource dataSourceHA; - - private String MASTER_URL = "jdbc:mock:master"; - private String SLAVE_URL = "jdbc:mock:slave"; - - protected void setUp() throws Exception { - for (DruidDataSource item : DruidDataSourceStatManager.getDruidDataSourceInstances()) { - JdbcUtils.close(item); - } - Assert.assertEquals(0, DruidDataSourceStatManager.getInstance().getDataSourceList().size()); - - dataSourceA = new DruidDataSource(); - dataSourceA.setUrl(MASTER_URL); - dataSourceA.setFilters("trace"); - - dataSourceB = new DruidDataSource(); - dataSourceB.setUrl(SLAVE_URL); - dataSourceB.setFilters("stat"); - - dataSourceHA = new HADataSource(); - dataSourceHA.setMaster(dataSourceA); - dataSourceHA.setSlave(dataSourceB); - } - - protected void tearDown() throws Exception { - dataSourceHA.close(); - - for (DruidDataSource dataSource : DruidDataSourceStatManager.getDruidDataSourceInstances()) { - dataSource.close(); - } - - Assert.assertEquals(0, DruidDataSourceStatManager.getInstance().getDataSourceList().size()); - } - - public void test_switch() throws Exception { - { - Connection conn = dataSourceHA.getConnection(); - - Statement stmt = conn.createStatement(); - stmt.execute("select 1"); - - MockConnection mockConn = conn.unwrap(MockConnection.class); - Assert.assertNotNull(mockConn); - - // Assert.assertEquals(dataSourceA.getUrl(), mockConn.getUrl()); - - conn.close(); - } - dataSourceHA.setMasterEnable(false); - { - Connection conn = dataSourceHA.getConnection(); - - Statement stmt = conn.createStatement(); - stmt.execute("select 1"); - - MockConnection mockConn = conn.unwrap(MockConnection.class); - Assert.assertNotNull(mockConn); - - // Assert.assertEquals(dataSourceB.getUrl(), mockConn.getUrl()); - - conn.close(); - } - } -} diff --git a/src/test/java/com/alibaba/druid/bvt/pool/ha/MultiDataSourceTest.java b/src/test/java/com/alibaba/druid/bvt/pool/ha/MultiDataSourceTest.java deleted file mode 100644 index d29a28aa42..0000000000 --- a/src/test/java/com/alibaba/druid/bvt/pool/ha/MultiDataSourceTest.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.bvt.pool.ha; - -import junit.framework.TestCase; - -import com.alibaba.druid.pool.ha.MultiDataSource; -import com.alibaba.druid.util.JdbcUtils; - - -public class MultiDataSourceTest extends TestCase { - public void test_0 () throws Exception { - MultiDataSource multiDataSource = new MultiDataSource(); - multiDataSource.close(); - } -} diff --git a/src/test/java/com/alibaba/druid/pool/ha/CobarDataSourceTest.java b/src/test/java/com/alibaba/druid/pool/ha/CobarDataSourceTest.java deleted file mode 100644 index d2ba3d9bfa..0000000000 --- a/src/test/java/com/alibaba/druid/pool/ha/CobarDataSourceTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool.ha; - -import java.sql.Connection; -import java.sql.Statement; -import java.util.concurrent.CountDownLatch; - -import junit.framework.TestCase; - -import com.alibaba.druid.pool.ha.cobar.CobarDataSource; - -public class CobarDataSourceTest extends TestCase { - - public void test_cobar() throws Exception { - String url = "jdbc:cobar://10.20.165.79:8080/druid"; - - final CobarDataSource dataSource = new CobarDataSource(); - dataSource.setUrl(url); - dataSource.setUsername("test"); - dataSource.setPassword(""); - - final int COUNT = 10; - final CountDownLatch latch = new CountDownLatch(COUNT); - - Runnable task = new Runnable() { - - public void run() { - try { - for (int i = 0; i < 1000 * 1000; ++i) { - Connection conn = dataSource.getConnection(); - - Statement stmt = conn.createStatement(); - stmt.execute("select 1"); - stmt.close(); - - conn.close(); - } - } catch (Exception ex) { - ex.printStackTrace(); - } finally { - latch.countDown(); - } - } - }; - - - for (int i = 0; i < 10; ++i) { - Thread thread = new Thread(task); - thread.setName("thread-" + i); - thread.start(); - } - - latch.await(); - } -}