java.lang.reflect.Proxy

本文详细介绍了如何使用Java SQL连接实现负载均衡,包括URL解析、主机列表生成及代理连接实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	private java.sql.Connection connectLoadBalanced(String url, Properties info)
throws SQLException
{
Properties parsedProps = parseURL(url, info);

// People tend to drop this in, it doesn't make sense
parsedProps.remove("roundRobinLoadBalance");

if (parsedProps == null)
{
return null;
}

int numHosts = Integer.parseInt(parsedProps
.getProperty(NUM_HOSTS_PROPERTY_KEY));

List hostList = new ArrayList();

for (int i = 0; i < numHosts; i++)
{
int index = i + 1;

hostList.add(parsedProps.getProperty(HOST_PROPERTY_KEY + "."
+ index)
+ ":"
+ parsedProps.getProperty(PORT_PROPERTY_KEY + "." + index));
}

LoadBalancingConnectionProxy proxyBal = new LoadBalancingConnectionProxy(
hostList, parsedProps);

return (java.sql.Connection) java.lang.reflect.Proxy.newProxyInstance(
this.getClass().getClassLoader(), new Class[]
{ com.mysql.jdbc.Connection.class }, proxyBal);
}


	protected java.sql.Connection connectReplicationConnection(String url,
Properties info) throws SQLException
{
Properties parsedProps = parseURL(url, info);

if (parsedProps == null)
{
return null;
}

Properties masterProps = (Properties) parsedProps.clone();
Properties slavesProps = (Properties) parsedProps.clone();

// Marker used for further testing later on, also when
// debugging
slavesProps.setProperty("com.mysql.jdbc.ReplicationConnection.isSlave",
"true");

int numHosts = Integer.parseInt(parsedProps
.getProperty(NUM_HOSTS_PROPERTY_KEY));

if (numHosts < 2)
{
throw SQLError
.createSQLException(
"Must specify at least one slave host to connect to for master/slave replication load-balancing functionality",
SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE,
null);
}

for (int i = 1; i < numHosts; i++)
{
int index = i + 1;

masterProps.remove(HOST_PROPERTY_KEY + "." + index);
masterProps.remove(PORT_PROPERTY_KEY + "." + index);

slavesProps.setProperty(HOST_PROPERTY_KEY + "." + i, parsedProps
.getProperty(HOST_PROPERTY_KEY + "." + index));
slavesProps.setProperty(PORT_PROPERTY_KEY + "." + i, parsedProps
.getProperty(PORT_PROPERTY_KEY + "." + index));
}

masterProps.setProperty(NUM_HOSTS_PROPERTY_KEY, "1");
slavesProps.remove(HOST_PROPERTY_KEY + "." + numHosts);
slavesProps.remove(PORT_PROPERTY_KEY + "." + numHosts);
slavesProps.setProperty(NUM_HOSTS_PROPERTY_KEY, String
.valueOf(numHosts - 1));
slavesProps.setProperty(HOST_PROPERTY_KEY, slavesProps
.getProperty(HOST_PROPERTY_KEY + ".1"));
slavesProps.setProperty(PORT_PROPERTY_KEY, slavesProps
.getProperty(PORT_PROPERTY_KEY + ".1"));

return new ReplicationConnection(masterProps, slavesProps);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值