初始化一次数据库连接对象并重用它 - jboss

Ash*_*win 2 java jboss servlets

我使用jboss服务器和postgresql作为数据库.现在我每次都在servlet中连接到数据库,如下所示:

public void doPost(HttpServletRequest req, HttpServletResponse resp)
{
Connection conn =null; // Create connection object
             String database = "jbossdb"; // Name of database
             String user = "qwerty"; //
             String password = "qwerty";
             String url = "jdbc:postgresql://localhost:5432/" + database;
             ResultSet rs = null;
             ResultSetMetaData rsm = null;
             ObjectInputStream in=new ObjectInputStream(req.getInputStream());
             String input=(String) in.readObject();
             String[] s_input=input.split(",");

              try{
                    Class.forName("org.postgresql.Driver").newInstance();
                    //.newInstance()
                 } catch(Exception e) 
                    {
                    System.err.println(e);
                    }

            try{
                conn = DriverManager.getConnection(url, user, password);

                }catch(SQLException se) 
                 {
                        System.err.println(se);
                 }
Run Code Online (Sandbox Code Playgroud)

这个代码存在于我的每个服务中.对于每个请求,都会创建一个新的连接对象.这会影响性能吗?在jboss中是否有任何方法只能初始化连接(可能在启动时),然后在需要时传递给servlet?我应该把它放在init()servlet 的方法中吗?

Jay*_*dee 5

更好的方法是使用连接池.您还需要确保正确关闭连接(如果发生这种情况,则代码中不清楚,仍需要使用池).至于存储连接,这不是一个好主意,因为你的servlet是多线程的(我很难学到这一点),你需要同步所有访问,这将是一个灾难.

http://geekexplains.blogspot.co.uk/2008/06/what-is-connection-pooling-why-do-we.html

http://confluence.atlassian.com/display/DOC/Configuring+a+PostgreSQL+Datasource+in+Apache+Tomcat

http://www.devdaily.com/blog/post/java/how-configure-tomcat-dbcp-connection-pool-pooling-postgres

--EDIT--为什么不在"init()"中这样做?

了解"servlet的生命周期".

只有在容器设置servlet时,才调用init()一次.

每个请求使用相同的servlet,而不是每个请求的新实例.因此不会为请求调用init().

由于每个请求都由同一个servlet实例处理,因此您的代码需要是多线程的.


Kri*_*han 5

您在这里可能不是一个好的解决方案。当您使用servlet来执行应用程序加载的某些操作时,可以具有侦听器。您要做的是,首先创建一个实现ServletContextListener的类。

public class ContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context=sce.getServletContext();
        String dburl=context.getInitParameter("dbUrl");
        String dbusername=context.getInitParameter("dbUserName");
        String dbpassword=context.getInitParameter("dbPassword");

        DBConnector.createConnection(dburl, dbusername, dbpassword);
        System.out.println("Connection Establised.........");
    }

    public void contextDestroyed(ServletContextEvent sce) {
        DBConnector.closeConnection();
    }

}
Run Code Online (Sandbox Code Playgroud)

之后,您可以创建另一个类以在应用程序加载时创建连接。

public class DBConnector {

    private static Connection con;

    public static void createConnection(String dbUrl,String dbusername,String dbPassword){
        try {
            Class.forName("org.postgresql.Driver");
            con=DriverManager.getConnection(dbUrl, dbusername, dbPassword);     
        } catch (Exception ex) {
            ex.printStackTrace();
        }    
    }

    public static Connection getConnection(){
        return con;
    }

    public static void closeConnection(){
        if(con!=null){
            try {
                con.close();
            } catch (SQLException ex) {
                 ex.printStackTrace();
            }
        }

    }



}
Run Code Online (Sandbox Code Playgroud)

然后,无论何时要获取数据库连接,都可以调用静态getConnection方法并获取它。为了调用您的侦听器类,您必须在web.xml内添加侦听器标签。

<context-param>
    <param-name>dbUrl</param-name>
    <param-value>jdbc:postgresql://localhost:5432/jbossdb</param-value>
</context-param>
<context-param>
    <param-name>dbUserName</param-name>
    <param-value>qwerty</param-value>
</context-param>
<context-param>
    <param-name>dbPassword</param-name>
    <param-value>qwerty</param-value>
</context-param>
<listener>
    <listener-class>com.icbt.bookstore.listener.ContextListener</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)

硬编码数据库用户名和密码不是一个好习惯。相反,您可以如图所示在web.xml中使用servlet初始化参数。

希望这能回答您的问题。