繼續之前的博文,
我們這裏用的是mysql數據庫,首先得導入mysql驅動jar包 mysql-connector-java-6.0.6.jar。
1、編寫一個JDBC連接池ConnectionPool
package com.dyw.crawler.util;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Vector;
/**
* 數據庫連接池
* Created by dyw on 2017/9/11.
*/
public class ConnectionPool {
private String jdbcDriver = ""; // 數據庫驅動
private String dbUrl = ""; // 數據 URL
private String dbUsername = ""; // 數據庫用戶名
private String dbPassword = ""; // 數據庫用戶密碼
private String testTable = ""; // 測試連接是否可用的測試表名,默認沒有測試表
private int initialConnections = 10; // 連接池的初始大小
private int incrementalConnections = 5;// 連接池自動增加的大小
private int maxConnections = 50; // 連接池最大的大小
private Vector connections = null; // 存放連接池中數據庫連接的向量 , 初始時爲 null
// 它中存放的對象爲 PooledConnection 型
/**
* 構造函數
*
* @param jdbcDriver String JDBC 驅動類串
* @param dbUrl String 數據庫 URL
* @param dbUsername String 連接數據庫用戶名
* @param dbPassword String 連接數據庫用戶的密碼
*/
public ConnectionPool(String jdbcDriver, String dbUrl, String dbUsername,
String dbPassword) {
this.jdbcDriver = jdbcDriver;
this.dbUrl = dbUrl;
this.dbUsername = dbUsername;
this.dbPassword = dbPassword;
}
/**
* 返回連接池的初始大小
*
* @return 初始連接池中可獲得的連接數量
*/
public int getInitialConnections() {
return this.initialConnections;
}
/**
* 設置連接池的初始大小
*
* @param initialConnections 用於設置初始連接池中連接的數量
*/
public void setInitialConnections(int initialConnections) {
this.initialConnections = initialConnections;
}
/**
* 返回連接池自動增加的大小 、
*
* @return 連接池自動增加的大小
*/
public int getIncrementalConnections() {
return this.incrementalConnections;
}
/**
* 設置連接池自動增加的大小
*
* @param incrementalConnections 連接池自動增加的大小
*/
public void setIncrementalConnections(int incrementalConnections) {
this.incrementalConnections = incrementalConnections;
}
/**
* 返回連接池中最大的可用連接數量
*
* @return 連接池中最大的可用連接數量
*/
public int getMaxConnections() {
return this.maxConnections;
}
/**
* 設置連接池中最大可用的連接數量
*
* @param maxConnections 設置連接池中最大可用的連接數量值
*/
public void setMaxConnections(int maxConnections) {
this.maxConnections = maxConnections;
}
/**
* 獲取測試數據庫表的名字
*
* @return 測試數據庫表的名字
*/
public String getTestTable() {
return this.testTable;
}
/**
* 設置測試表的名字
*
* @param testTable String 測試表的名字
*/
public void setTestTable(String testTable) {
this.testTable = testTable;
}
/**
* 創建一個數據庫連接池,連接池中的可用連接的數量採用類成員 initialConnections 中設置的值
*/
public synchronized void createPool() throws Exception {
// 確保連接池沒有創建
// 如果連接池己經創建了,保存連接的向量 connections 不會爲空
if (connections != null) {
return; // 如果己經創建,則返回
}
// 實例化 JDBC Driver 中指定的驅動類實例
Driver driver = (Driver) (Class.forName(this.jdbcDriver).newInstance());
DriverManager.registerDriver(driver); // 註冊 JDBC 驅動程序
// 創建保存連接的向量 , 初始時有 0 個元素
connections = new Vector();
// 根據 initialConnections 中設置的值,創建連接。
createConnections(this.initialConnections);
// System.out.println(" 數據庫連接池創建成功! ");
}
/**
* 創建由 numConnections 指定數目的數據庫連接 , 並把這些連接 放入 connections 向量中
*
* @param numConnections 要創建的數據庫連接的數目
*/
@SuppressWarnings("unchecked")
private void createConnections(int numConnections) throws SQLException {
// 循環創建指定數目的數據庫連接
for (int x = 0; x < numConnections; x++) {
// 是否連接池中的數據庫連接的數量己經達到最大?最大值由類成員 maxConnections
// 指出,如果 maxConnections 爲 0 或負數,表示連接數量沒有限制。
// 如果連接數己經達到最大,即退出。
if (this.maxConnections > 0
&& this.connections.size() >= this.maxConnections) {
break;
}
// add a new PooledConnection object to connections vector
// 增加一個連接到連接池中(向量 connections 中)
try {
connections.addElement(new PooledConnection(newConnection()));
} catch (SQLException e) {
System.out.println(" 創建數據庫連接失敗! " + e.getMessage());
throw new SQLException();
}
// System.out.println(" 數據庫連接己創建 ......");
}
}
/**
* 創建一個新的數據庫連接並返回它
*
* @return 返回一個新創建的數據庫連接
*/
private Connection newConnection() throws SQLException {
// 創建一個數據庫連接
Connection conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
// 如果這是第一次創建數據庫連接,即檢查數據庫,獲得此數據庫允許支持的
// 最大客戶連接數目
// connections.size()==0 表示目前沒有連接己被創建
if (connections.size() == 0) {
DatabaseMetaData metaData = conn.getMetaData();
int driverMaxConnections = metaData.getMaxConnections();
// 數據庫返回的 driverMaxConnections 若爲 0 ,表示此數據庫沒有最大
// 連接限制,或數據庫的最大連接限制不知道
// driverMaxConnections 爲返回的一個整數,表示此數據庫允許客戶連接的數目
// 如果連接池中設置的最大連接數量大於數據庫允許的連接數目 , 則置連接池的最大
// 連接數目爲數據庫允許的最大數目
if (driverMaxConnections > 0
&& this.maxConnections > driverMaxConnections) {
this.maxConnections = driverMaxConnections;
}
}
return conn; // 返回創建的新的數據庫連接
}
/**
* 通過調用 getFreeConnection() 函數返回一個可用的數據庫連接 , 如果當前沒有可用的數據庫連接,並且更多的數據庫連接不能創
* 建(如連接池大小的限制),此函數等待一會再嘗試獲取。
*
* @return 返回一個可用的數據庫連接對象
*/
public synchronized Connection getConnection() throws SQLException {
// 確保連接池己被創建
if (connections == null) {
return null; // 連接池還沒創建,則返回 null
}
Connection conn = getFreeConnection(); // 獲得一個可用的數據庫連接
// 如果目前沒有可以使用的連接,即所有的連接都在使用中
while (conn == null) {
// 等一會再試
// System.out.println("Wait");
wait(250);
conn = getFreeConnection(); // 重新再試,直到獲得可用的連接,如果
// getFreeConnection() 返回的爲 null
// 則表明創建一批連接後也不可獲得可用連接
}
return conn;// 返回獲得的可用的連接
}
/**
* 本函數從連接池向量 connections 中返回一個可用的的數據庫連接,如果 當前沒有可用的數據庫連接,本函數則根據
* incrementalConnections 設置 的值創建幾個數據庫連接,並放入連接池中。 如果創建後,所有的連接仍都在使用中,則返回 null
*
* @return 返回一個可用的數據庫連接
*/
private Connection getFreeConnection() throws SQLException {
// 從連接池中獲得一個可用的數據庫連接
Connection conn = findFreeConnection();
if (conn == null) {
// 如果目前連接池中沒有可用的連接
// 創建一些連接
createConnections(incrementalConnections);
// 重新從池中查找是否有可用連接
conn = findFreeConnection();
if (conn == null) {
// 如果創建連接後仍獲得不到可用的連接,則返回 null
return null;
}
}
return conn;
}
/**
* 查找連接池中所有的連接,查找一個可用的數據庫連接, 如果沒有可用的連接,返回 null
*
* @return 返回一個可用的數據庫連接
*/
private Connection findFreeConnection() throws SQLException {
Connection conn = null;
PooledConnection pConn = null;
// 獲得連接池向量中所有的對象
Enumeration enumerate = connections.elements();
// 遍歷所有的對象,看是否有可用的連接
while (enumerate.hasMoreElements()) {
pConn = (PooledConnection) enumerate.nextElement();
if (!pConn.isBusy()) {
// 如果此對象不忙,則獲得它的數據庫連接並把它設爲忙
conn = pConn.getConnection();
pConn.setBusy(true);
// 測試此連接是否可用
if (!testConnection(conn)) {
// 如果此連接不可再用了,則創建一個新的連接,
// 並替換此不可用的連接對象,如果創建失敗,返回 null
try {
conn = newConnection();
} catch (SQLException e) {
System.out.println(" 創建數據庫連接失敗! " + e.getMessage());
return null;
}
pConn.setConnection(conn);
}
break; // 己經找到一個可用的連接,退出
}
}
return conn;// 返回找到到的可用連接
}
/**
* 測試一個連接是否可用,如果不可用,關掉它並返回 false 否則可用返回 true
*
* @param conn 需要測試的數據庫連接
* @return 返回 true 表示此連接可用, false 表示不可用
*/
private boolean testConnection(Connection conn) {
try {
// 判斷測試表是否存在
if (testTable.equals("")) {
// 如果測試表爲空,試着使用此連接的 setAutoCommit() 方法
// 來判斷連接否可用(此方法只在部分數據庫可用,如果不可用 ,
// 拋出異常)。注意:使用測試表的方法更可靠
conn.setAutoCommit(true);
} else {// 有測試表的時候使用測試表測試
// check if this connection is valid
Statement stmt = conn.createStatement();
stmt.execute("select count(*) from " + testTable);
}
} catch (SQLException e) {
// 上面拋出異常,此連接己不可用,關閉它,並返回 false;
closeConnection(conn);
return false;
}
// 連接可用,返回 true
return true;
}
/**
* 此函數返回一個數據庫連接到連接池中,並把此連接置爲空閒。 所有使用連接池獲得的數據庫連接均應在不使用此連接時返回它。
*
* @param conn 需返回到連接池中的連接對象
*/
public void returnConnection(Connection conn) {
// 確保連接池存在,如果連接沒有創建(不存在),直接返回
if (connections == null) {
System.out.println(" 連接池不存在,無法返回此連接到連接池中 !");
return;
}
PooledConnection pConn = null;
Enumeration enumerate = connections.elements();
// 遍歷連接池中的所有連接,找到這個要返回的連接對象
while (enumerate.hasMoreElements()) {
pConn = (PooledConnection) enumerate.nextElement();
// 先找到連接池中的要返回的連接對象
if (conn == pConn.getConnection()) {
// 找到了 , 設置此連接爲空閒狀態
pConn.setBusy(false);
break;
}
}
}
/**
* 刷新連接池中所有的連接對象
*/
public synchronized void refreshConnections() throws SQLException {
// 確保連接池己創新存在
if (connections == null) {
System.out.println(" 連接池不存在,無法刷新 !");
return;
}
PooledConnection pConn = null;
Enumeration enumerate = connections.elements();
while (enumerate.hasMoreElements()) {
// 獲得一個連接對象
pConn = (PooledConnection) enumerate.nextElement();
// 如果對象忙則等 5 秒 ,5 秒後直接刷新
if (pConn.isBusy()) {
wait(5000); // 等 5 秒
}
// 關閉此連接,用一個新的連接代替它。
closeConnection(pConn.getConnection());
pConn.setConnection(newConnection());
pConn.setBusy(false);
}
}
/**
* 關閉連接池中所有的連接,並清空連接池。
*/
public synchronized void closeConnectionPool() throws SQLException {
// 確保連接池存在,如果不存在,返回
if (connections == null) {
System.out.println(" 連接池不存在,無法關閉 !");
return;
}
PooledConnection pConn = null;
Enumeration enumerate = connections.elements();
while (enumerate.hasMoreElements()) {
pConn = (PooledConnection) enumerate.nextElement();
// 如果忙,等 5 秒
if (pConn.isBusy()) {
wait(5000); // 等 5 秒
}
// 5 秒後直接關閉它
closeConnection(pConn.getConnection());
// 從連接池向量中刪除它
connections.removeElement(pConn);
}
// 置連接池爲空
connections = null;
}
/**
* 關閉一個數據庫連接
*
* @param conn 需要關閉的數據庫連接
*/
private void closeConnection(Connection conn) {
try {
conn.close();
} catch (SQLException e) {
System.out.println(" 關閉數據庫連接出錯: " + e.getMessage());
}
}
/**
* 使程序等待給定的毫秒數
*
* @param mSeconds 給定的毫秒數
*/
private void wait(int mSeconds) {
try {
Thread.sleep(mSeconds);
} catch (InterruptedException e) {
}
}
/**
* 內部使用的用於保存連接池中連接對象的類 此類中有兩個成員,一個是數據庫的連接,另一個是指示此連接是否 正在使用的標誌。
*/
class PooledConnection {
Connection connection = null;// 數據庫連接
boolean busy = false; // 此連接是否正在使用的標誌,默認沒有正在使用
// 構造函數,根據一個 Connection 構告一個 PooledConnection 對象
public PooledConnection(Connection connection) {
this.connection = connection;
}
// 返回此對象中的連接
public Connection getConnection() {
return connection;
}
// 設置此對象的,連接
public void setConnection(Connection connection) {
this.connection = connection;
}
// 獲得對象連接是否忙
public boolean isBusy() {
return busy;
}
// 設置對象的連接正在忙
public void setBusy(boolean busy) {
this.busy = busy;
}
}
}
2、main主程序
package com.dyw.crawler.project;
import com.dyw.crawler.util.ConnectionPool;
import com.dyw.crawler.util.CrawlerUtils;
import com.dyw.crawler.util.IOUtils;
import com.dyw.crawler.util.RegularUtils;
import java.io.File;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.util.List;
/**
* 保存爬蟲的文件信息保存到數據庫
* Created by dyw on 2017/9/11.
*/
public class Project4 {
private static String url = "jdbc:mysql://localhost:3306/crawler?characterEncoding=utf8&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
private static String username = "root";
private static String password = "root";
private static String driver = "com.mysql.jdbc.Driver";
public static void main(String[] args) throws Exception {
// 創建數據庫連接池對象
ConnectionPool connPool = new ConnectionPool(driver, url, username, password);
// 新建數據庫連接
connPool.createPool();
// SQL
String insertSql = "insert into img (url,file_name,create_date,path) values (?,?,?,?)";
//文件放置的路徑
String path = "C:\\Users\\dyw\\Desktop\\crawler\\photo5";
//爬取的網站地址
String url = "http://www.gravuregirlz.com/145741/song-guo-%E6%9D%BE%E6%9E%9C%E5%84%BFcc-naked-uncensored-unreleased-tuigirl-sets/";
//獲取內容
String htmlContent = null;
try {
htmlContent = CrawlerUtils.get(url);
} catch (Exception e) {
throw new RuntimeException("獲取內容失敗!", e);
}
//獲取所有的img的內容
List<String> imgUrls = RegularUtils.getIMGUrl(htmlContent);
//分別下載每個img
imgUrls.forEach(imgUrl -> {
if (!imgUrl.startsWith("http")) {
imgUrl = url + imgUrl;
}
String[] split = imgUrl.split("/");
String imgName = split[split.length - 1];
try {
File file1 = new File(path + "/" + imgName);
InputStream inputStream = CrawlerUtils.downLoadFromUrl(imgUrl);
IOUtils.saveFile(inputStream, file1);
System.out.println("success:" + imgUrl);
// 從連接庫中獲取一個可用的連接
Connection conn = connPool.getConnection();
PreparedStatement preparedStatement = conn.prepareStatement(insertSql);
preparedStatement.setString(new Integer(1), imgUrl);
preparedStatement.setString(new Integer(2), imgName);
preparedStatement.setDate(new Integer(3), new Date(System.currentTimeMillis()));
preparedStatement.setString(new Integer(4), path);
preparedStatement.executeUpdate();
preparedStatement.close();
connPool.returnConnection(conn); // 連接使用完後釋放連接到連接池
} catch (Exception e) {
System.out.println("fail:" + imgUrl);
}
});
}
}
如果對本文中方法有不瞭解的可以看之前的爬蟲記錄系列文章,有具體代碼。
具體代碼我上傳在github上,需要完整代碼的可以自己下載 https://github.com/dingyinwu81/crawler
如果有什麼代碼修改的建議,請給我留言唄! ☺☺☺