【发布时间】:2012-11-14 22:18:21
【问题描述】:
大家好,我有一个基本的 Storm 应用程序设置,它接收推文流并将它们存储在 MySQL 数据库中。该应用程序在前约 23 小时内运行良好,然后开始出现以下错误:
SQL Exception
SQL State: 08003
在它这样做几次之后它就死了。我正在使用标准 JBDC 连接器从 Java 连接到数据库。存储和建立DB连接的函数代码如下:
private String _db="";
private Connection conn = null;
private PreparedStatement pst = null;
public ArchiveBolt(String db){
_db = db;
}
private void setupConnection() {
//Connect to the database
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:8889/twitter_recording", "root", "root");
} catch (Exception e){
e.printStackTrace();
}
}
public void execute(Tuple tuple, BasicOutputCollector collector) {
Status s = (Status) tuple.getValue(0);
//setup the connection on the first run through or if the connection got closed down
try {
setupConnection();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
}
try {
pst = conn.prepareStatement("INSERT INTO " + _db + " (tweet)" +
"VALUES (?);");
pst.setString(1, s.toString());
//execute the SQL
pst.executeUpdate();
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
if(ex.getSQLState().equals("08003")){
setupConnection();
}
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
在很明显它由于 08003 错误而崩溃后,我决定如果它抛出该错误,它应该重试连接设置,但这也无济于事。谁能指出我解决这个问题的正确方向?
【问题讨论】:
-
连接是否总是在一天中的同一时间断开?如果是这样,则连接可能被某些预定事件中断(例如,数据库每天都会重新启动)。
-
是的,我知道这一点。这就是为什么在遇到此错误的情况下再次设置连接的原因。如上图
catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); if(ex.getSQLState().equals("08003")){ setupConnection(); } } -
如果每天重启,数据库可能会宕机几分钟,尝试立即重新连接会失败。
-
连接不会在每天的同一时间断开。从我开始它总是大约 23 小时。我控制数据库,在项目的这个阶段,它持续 24/7 持续运行。
标签: java mysql jdbc apache-storm