因为项目中有多个cobar节点,现在只是连接的单一cobar节点,想修改为连接多个cobar节点,失败后,自动切换至其它节点。
原来看druid时,印象中有druid-ha,高高兴兴拿过来用,发现无法使用,再看源码,发现根本就没实现嘛。
在网上搜索了下,相关的资源也不是非常多。
好在需求很简单可以自已来造个轮子。
代码如下:
package cn.joylab.game.util;
import java.sql.Connection;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.datasource.AbstractDataSource;
public class HADataSource extends AbstractDataSource {
private List<DataSource> targetDataSources;
private int index = RandomUtils.nextInt(2);
public List<DataSource> getTargetDataSources() {
return targetDataSources;
}
public void setTargetDataSources(List<DataSource> targetDataSources) {
this.targetDataSources = targetDataSources;
}
public Connection getConnection() {
log.info("getConnection()");
for (int m = 0; m < targetDataSources.size(); m++) {
try {
DataSource dataSource = targetDataSources.get(index);
Connection conn = dataSource.getConnection();
log.info("getConnenction success from index : " + index);
return conn;
} catch (Exception e) {
index = (++index) % targetDataSources.size();
log.error("ERROR", e);
}
}
throw new RuntimeException("db connection error");
}
public Connection getConnection(String username, String password) {
log.info("getConnection() with username and password");
return null;
}
private static final Log log = LogFactory.getLog(HADataSource.class);
}
只是简单的进行下datasource的切换。
0 条评论。