【发布时间】:2016-04-17 01:43:05
【问题描述】:
我正在构建一个网络爬虫,我正在寻找处理我的请求以及我的线程和数据库 (MySql) 之间的连接的最佳方式。
我有两种类型的线程:
- Fetchers:他们抓取网站。他们生成 url 并将它们添加到 2 个表中:table_url 和 table_file。他们从 table_url 中选择 继续爬行。并更新 table_url 以设置visited=1 当他们 已阅读网址。或者在他们阅读时访问了=-1。他们能 删除行。
- 下载器:他们下载文件。他们从 table_file 中选择。他们更新 table_file 以更改 Downloaded 列。他们从不 插入任何东西。
现在我正在处理这个: 我有一个基于c3p0 的连接池。 每个目标(网站)都有这些变量:
private Connection connection_downloader;
private Connection connection_fetcher;
当我实例化一个网站时,我只创建一次这两个连接。然后每个线程将根据他们的目标使用这些连接。
每个线程都有这些变量:
private Statement statement;
private ResultSet resultSet;
在每次查询之前,我都会打开一个 SqlStatement:
public static Statement openSqlStatement(Connection connection){
try {
return connection.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
在每次查询之后,我都会关闭 sql 语句和 resultSet :
public static void closeSqlStatement(ResultSet resultSet, Statement statement){
if (resultSet != null) try { resultSet.close(); } catch (SQLException e) {e.printStackTrace();}
if (statement != null) try { statement.close(); } catch (SQLException e) {e.printStackTrace();}
}
现在我的 Select 查询只适用于一个选择(我现在不必选择多个,但很快就会改变)并且定义如下:
public static String sqlSelect(String Query, Connection connection, Statement statement, ResultSet resultSet){
String result = null;
try {
resultSet = statement.executeQuery(Query);
resultSet.next();
result = resultSet.toString();
} catch (SQLException e) {
e.printStackTrace();
}
closeSqlStatement(resultSet, statement);
return result;
}
插入、删除和更新查询使用此功能:
public static int sqlExec(String Query, Connection connection, Statement statement){
int ResultSet = -1;
try {
ResultSet = statement.executeUpdate(Query);
} catch (SQLException e) {
e.printStackTrace();
}
closeSqlStatement(resultSet, statement);
return ResultSet;
}
我的问题很简单:这可以改进得更快吗?而且我担心互斥会阻止一个线程在另一个线程更新链接时更新链接。
【问题讨论】:
标签: java mysql multithreading jdbc