第一步:根据核心分离参数 id(String)与action得到一个连接。
对ID与action的处理如下:
...
public static Logger log = Logger.getLogger(QueryRoute.class);
//parameter
//id type eg: u-2818219 --> user object
private String id;
//get action
private String action;
public QueryRoute(String id){
this.id= id;
this.action = "";
}
public QueryRoute(String id,String action){
this.id = id.toLowerCase();
this.action = action.toLowerCase();
}
public Connection getConnection(){
String object_type = id.split("-")[0];
long number_id = Long.parseLong(id.split("-")[1]);
Connection conn = null;
if(object_type.equals("u")){
if(this.action.equals("select")){
try {
log.info("SERVER:"+SchemaDivision.getSchemaIndex(number_id));
conn = DataBasePool.getRead_pools().get("server_"+SchemaDivision.getSchemaIndex(number_id)).getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(this.action.equals("")){
try {
conn = DataBasePool.getPools().get("server_"+SchemaDivision.getSchemaIndex(number_id)).getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(this.action.equals("insert")||this.action.equals("update")||this.action.equals("delete")){
try {
conn = DataBasePool.getWrite_pools().get("server_"+SchemaDivision.getSchemaIndex(number_id)).getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return conn;
}
这样既通过之前配置好的server_node来确认具体连接的节点。 然后从连接池中取出这样的Connection
本地数据库中的测试数据如下:
下面是运行的console:
总结:
整体运行的结果是正确的。但是有几个问题需要解决:
1:未解决单库分表的问题。
2:为能基于xml定义规则的路由访问(仅通过代码部分实现)
接下来要做的事应该有以下:
一:定义xml路由规则部分,解决需要大量代码定义不同规则的问题。
二:解决单库分表的路由问题。