在java中轮询程序的数据库连接的最佳方法是什么

时间:2014-09-17 10:51:35

标签: java jdbc

我正在使用TimerTask在java中创建一个轮询程序,以便自动发送电子邮件和其他通知。现在这个程序每秒检查数据库是否有任何可用的新数据。

现在我正在创建如下所示的连接

Connector类,它保存数据库详细信息并返回连接。

public class Connector implements Serializable {

    private static final long serialVersionUID = 1L;
    private ResourceBundle prop = ResourceBundle.getBundle("dbdetails");

    public Connection getConnection() throws Exception {
        Connection con;
        Class.forName((String) prop.getString("DB_DRIVER"));
        con = DriverManager.getConnection((String) prop.getString("DB_URL"),
                (String) prop.getString("DB_USER"),
                (String) prop.getString("DB_PASS"));
        return con;

    }

}

我的投票类

public class EmailPoller extends TimerTask {
    private static Logger logger = Logger.getLogger(EmailPoller.class);
    private Connector connector = new Connector();

    @Override
    public void run() {
        Connection con = null;
        PreparedStatement ps = null, ps1 = null;
        ResultSet rs = null;
        try {
            con = connector.getConnection();
            ps = con.prepareStatement("select to_addr,subject,content,id from email_notification where status='A'");
            ps1 = con
                    .prepareStatement("update email_notification set status='I' where id=?");
            rs = ps.executeQuery();
            while (rs.next()) {
                Boolean b = Mailer.sendMail(rs.getString(1), rs.getString(2),
                        rs.getString(3));

                if (b) {
                    ps1.setInt(1, rs.getInt(4));
                    ps1.executeUpdate();
                }
            }
        } catch (Exception ex) {
            logger.info("Email Poller Error : " + ex);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (ps1 != null) {
                    ps1.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (Exception ex) {
                logger.info("Email Poller Error : " + ex);
            }
        }
    }
}

发送电子邮件后我正在更新标志。梅勒正在完美地发送邮件。

这是否是检查数据库中数据的正确方法还是以其他任何方式连接到数据库?

2 个答案:

答案 0 :(得分:1)

由于您需要在特定时间段轮询数据库, - 每次在数据库中寻找某些东西时,都不应该创建连接。创建一次连接并reuse,或让DataSource处理所有内容。您只需要为DataSource请求连接,它就会为您提供连接。

您可以稍微修改Connector类,如下所示,以允许DataSource实现处理连接池。

以下示例使用MySql Implementation of the DataSource interface。但是,您可以根据您使用的数据库更改实现,只需将相应的jar添加到类路径中即可。

    class Connector implements Serializable {

    private static final long serialVersionUID = 1L;
    private static ResourceBundle prop = ResourceBundle.getBundle("dbdetails");
    private static MysqlDataSource dataSource = null;

    // Dont allow any instance of this class
    private Connector(){
    }

    private static void initDataSource()
    {
        try 
        {
            dataSource = new MysqlDataSource();
            dataSource.setURL(prop.getString("DB_URL"));
            dataSource.setUser(prop.getString("DB_USER"));
            dataSource.setPassword(prop.getString("DB_PASS"));
        } 
        catch (SQLException e) {
            // handle the Exception according to your application demand
        }
    } 
    /*
     * Return a connection from the datasource pool 
     */
    public static Connection getConnection() throws Exception {
       if(dataSource == null)
       {
           initDataSource();
       }
       return dataSource.getConnection();
    }

}

虽然上述内容变得更有效,但更适合需要处理大量请求并汇总连接的web applications。由于您的程序是standalone code,您可以ignore连接池,只需确保您的应用程序在任何时候只有一个连接。您可以修改Connector类,如下所示:

class Connector implements Serializable {

private static final long serialVersionUID = 1L;
private static ResourceBundle prop = ResourceBundle.getBundle("dbdetails");;
private static Connection con = null;

// Dont allow any instance to be created for this class
private Connector(){
}

private static void initConnection() throws  Exception
{
    Class.forName((String) prop.getString("DB_DRIVER"));
    con = DriverManager.getConnection((String) prop.getString("DB_URL"),
            (String) prop.getString("DB_USER"),
            (String) prop.getString("DB_PASS"));
}

public static Connection getConnection() throws Exception {
    if(con == null)
    {
        initConnection();
    }
    return con;
}

}

按照Connector.getConnection()模式获取singleton连接。

答案 1 :(得分:0)

我不相信你的是最有效的联系方式。阅读有关连接池和计时器任务的信息,从池中获取更高效的连接,使您的工作在管理连接方面更加轻松。

对于初学者,您可以查看:this question

相关问题