在一般的java 項目 以及 現在特別火的大資料分析項目中 ,用到資料庫以及資料庫資源集區 串連的事情 是在稀鬆平常不過的了 。今天就簡單的梳理下 這是一個怎樣的過程:
我們按照代碼的調度順序審視下 :
Comment ,我們是從Spark 資料分析做demo 展開的 :
第一,假設讀寫資料庫一定是從業務層面發出的 ,那麼就應該有以下代碼
這是我們眾多代碼中的最後一步 ,寫資料到資料庫的代碼,將最後產生的資料寫入資料庫 ,假設現在資料庫類型不能,就要求我們提供可配置的功能了 ,the most impotent code I marked in red and bold
JavaPairRDD<String, Tuple2<String, Row>> sessionDetailRDD = top10SessionRDD.join(sessionid2detailRDD);sessionDetailRDD.foreach(new VoidFunction<Tuple2<String,Tuple2<String,Row>>>() { private static final long serialVersionUID = 1L; @Override public void call(Tuple2<String, Tuple2<String, Row>> tuple) throws Exception { Row row = tuple._2._2; SessionDetail sessionDetail = new SessionDetail(); sessionDetail.setTaskid(taskid); sessionDetail.setUserid(row.getLong(1)); 。。。。。。。、//reomve some contents ISessionDetailDAO sessionDetailDAO = DAOFactory.getSessionDetailDAO(); // sessionDetailDAO.insert(sessionDetail); }});
public static ISessionDetailDAO getSessionDetailDAO() { return new SessionDetailDAOImpl();} 第二 ,上面代碼來自DAOFactory 中定主意Impl 的實現
接下來讓看下 Impl 代碼是如何?的
第三 insert 中的資料是我們insert 到 DB 中的資料 ,在這裡要轉化成參數 跟sql 拼接起來
public class SessionDetailDAOImpl implements ISessionDetailDAO { /** * 插入一條資料 * @param sessionDetail */ public void insert(SessionDetail sessionDetail) { String sql = "insert into table_name values(?,?,?,?,?,?,?,?,?,?,?,?)"; Object[] params = new Object[]{sessionDetail.getTaskid(), sessionDetail.getUserid(), sessionDetail.getSessionid(), JDBCHelper jdbcHelper = JDBCHelper.getInstance(); jdbcHelper.executeUpdate(sql, params); }
第四,介紹下JDBChelper 是怎麼實現的 ,這一步需要到資料庫資源集區中擷取db 連結
import com.zkys.spark.conf.ConfigurationManager;import com.zkys.spark.constant.Constants;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.LinkedList;import java.util.List;public class JDBCHelper { static { try { String driver = ConfigurationManager.getProperty(Constants.JDBC_DRIVER); Class.forName(driver); } catch (Exception e) { e.printStackTrace(); } } private static JDBCHelper instance = null; public static JDBCHelper getInstance() { if(instance == null) { synchronized(JDBCHelper.class) { //synchronized http://www.cnblogs.com/GnagWang/archive/2011/02/27/1966606.html if(instance == null) { instance = new JDBCHelper();//調用私人無參構造方法 ,需要在構造方法中實現資料庫的連結 } } } return instance; } // 資料庫連接池 private LinkedList<Connection> datasource = new LinkedList<Connection>(); //對於新增和刪除操作add和remove,LinedList比較佔優勢,因為ArrayList要移動資料。 private JDBCHelper() { int datasourceSize = ConfigurationManager.getInteger( Constants.JDBC_DATASOURCE_SIZE); for(int i = 0; i < datasourceSize; i++) { boolean local = ConfigurationManager.getBoolean(Constants.SPARK_LOCAL); String url = null; String user = null; String password = null; url = ConfigurationManager.getProperty(Constants.JDBC_URL); user = ConfigurationManager.getProperty(Constants.JDBC_USER); password = ConfigurationManager.getProperty(Constants.JDBC_PASSWORD); try { //經過迴圈在這裡面建立了10 個資料庫連結 ,並把串連放到LinkList 裡面了 Connection conn = DriverManager.getConnection(url, user, password); datasource.push(conn); } catch (Exception e) { e.printStackTrace(); } } } public synchronized Connection getConnection() { while(datasource.size() == 0) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } return datasource.poll(); } public int executeUpdate(String sql, Object[] params) { int rtn = 0; Connection conn = null; PreparedStatement pstmt = null; try { conn = getConnection(); conn.setAutoCommit(false); pstmt = conn.prepareStatement(sql); if(params != null && params.length > 0) { for(int i = 0; i < params.length; i++) { pstmt.setObject(i + 1, params[i]); } } rtn = pstmt.executeUpdate(); conn.commit(); } catch (Exception e) { e.printStackTrace(); } finally { if(conn != null) { datasource.push(conn); } } return rtn; } public void executeQuery(String sql, Object[] params, QueryCallback callback) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = getConnection(); pstmt = conn.prepareStatement(sql); if(params != null && params.length > 0) { for(int i = 0; i < params.length; i++) { pstmt.setObject(i + 1, params[i]); } } rs = pstmt.executeQuery(); callback.process(rs); } catch (Exception e) { e.printStackTrace(); } finally { if(conn != null) { datasource.push(conn); } } } public int[] executeBatch(String sql, List<Object[]> paramsList) { int[] rtn = null; Connection conn = null; PreparedStatement pstmt = null; try { conn = getConnection(); // 第一步:使用Connection對象,取消自動認可 conn.setAutoCommit(false); pstmt = conn.prepareStatement(sql); // 第二步:使用PreparedStatement.addBatch()方法加入批量的SQL參數 if(paramsList != null && paramsList.size() > 0) { for(Object[] params : paramsList) { for(int i = 0; i < params.length; i++) { pstmt.setObject(i + 1, params[i]); } pstmt.addBatch(); } } // 第三步:使用PreparedStatement.executeBatch()方法,執行批量的SQL語句 rtn = pstmt.executeBatch(); // 最後一步:使用Connection對象,提交批量的SQL語句 conn.commit(); } catch (Exception e) { e.printStackTrace(); } finally { if(conn != null) { datasource.push(conn); } } return rtn; } /** * 靜態內部類:查詢回調介面 * @author Administrator * */ public static interface QueryCallback { /** * 處理查詢結果 * @param rs * @throws Exception */ void process(ResultSet rs) throws Exception; } }
第五,由於是可以配置的,所以需要加入更多元素
import java.io.InputStream;import java.util.Properties;public class ConfigurationManager { private static Properties prop = new Properties(); static { try { InputStream in = ConfigurationManager.class .getClassLoader().getResourceAsStream("my.properties"); prop.load(in); } catch (Exception e) { e.printStackTrace(); } } public static String getProperty(String key) { return prop.getProperty(key); } public static Integer getInteger(String key) { String value = getProperty(key); try { return Integer.valueOf(value); } catch (Exception e) { e.printStackTrace(); } return 0; } public static Boolean getBoolean(String key) { String value = getProperty(key); try { return Boolean.valueOf(value); } catch (Exception e) { e.printStackTrace(); } return false; } public static Long getLong(String key) { String value = getProperty(key); try { return Long.valueOf(value); } catch (Exception e) { e.printStackTrace(); } return 0L; } }