mysql jdbc failover

因为项目中有多个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 条评论。

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /opt/wordpress/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048