MySQL: Sharding 中间框架(基于XML配置文档) (0.1.2)

ID Generator


ID的生成策略参见:生成方法

简单的实现了其思想中的方法。


package dataSource.idGenerator;



import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;



import org.apache.log4j.Logger;



import dataBasePool.DataBasePool;

/*

 * ID Generator

 * You need two SQL server

 * Their config should be like the following:

 * Server 1:

auto-increment-increment = 2

auto-increment-offset = 1



   Server 2:

auto-increment-increment = 2

auto-increment-offset = 2

 *

 */

public class IDGenerator {




public static Logger log = Logger.getLogger(IDGenerator.class);

private  Connection[] conns;



public IDGenerator(){



try {

conns[0] = DataBasePool.getPools().get("id_server_1").getConnection();

conns[1] = DataBasePool.getPools().get("id_server_2").getConnection();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}



public long getPrimaryKey(){

//default id

long id = 1;



PreparedStatement pstmt = null;

String sql = "";

//use the system time to keep loading balancing



long current_time = System.currentTimeMillis()/1000;

Connection conn = null;

if(current_time % 2 == 0){

try {

conn = conns[0];

conn.setAutoCommit(false);

sql = "replace into id_sequence (stub) values('a')";

pstmt = conn.prepareStatement(sql);

pstmt.execute();

sql = "select last_insert_id()";

pstmt = conn.prepareStatement(sql);

ResultSet rs = pstmt.executeQuery();

if(rs.next()){

id = rs.getLong("last_insert_id()");

}

conn.commit();

log.info("Get ID: "+id);

} catch (SQLException e) {

e.printStackTrace();

}

}else{

try {

conn = conns[1];

sql = "replace into id_sequence (stub) values('a')";

pstmt = conn.prepareStatement(sql);

pstmt.execute();

sql = "select last_insert_id()";

   pstmt = conn.prepareStatement(sql);

ResultSet rs = pstmt.executeQuery();

if(rs.next()){

id = rs.getLong("last_insert_id()");

}



log.info("Get ID: "+id);

} catch (SQLException e) {

e.printStackTrace();

}

}

try {

conn.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return id;

}



public static void main(String[] args){

IDGenerator id_generator = new IDGenerator();

System.out.println(id_generator.getPrimaryKey());

System.out.println(id_generator.getPrimaryKey());

}

}
原文地址:https://www.cnblogs.com/-Doraemon/p/4700075.html