如何在Java Servlet应用程序上为每个用户创建一个数据库连接? [英] How to create one database connection per user on a Java Servlet application?

查看:173
本文介绍了如何在Java Servlet应用程序上为每个用户创建一个数据库连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个使用Java Servlets的网站上工作,研究表明,最好让每个用户保持一个数据库连接(而不是仅将一个连接一直保持在后台或每次连接到数据库时)需要进行交易)。但是,我不知道该如何完成。我目前正在做的是在数据访问对象类中,我有一个

I am working on a website using Java Servlets and my research showed me that it is best to keep one database connection per user (rather than have only one connection sitting all the time on the background or connect to the database every time that a transaction needs to be made). I don't know how to accomplish this, however. What I am currently doing is in my Data Access Object class I have a

private static Connection conn;

,而我有 HTTPSessionListener -在 sessionCreated 事件,我使用此静态 conn变量连接到数据库,在 sessionDestroyed 事件中,我断开了 conn连接变量:

and I have a HTTPSessionListener - on sessionCreated event I connect to the Database using this static "conn" variable, and on sessionDestroyed event I disconnect the "conn" variable:

...在我的 MySessionListener中...

...in my "MySessionListener"...

public void sessionCreated(HttpSessionEvent sessionEvent) {
    System.out.println("Session created!");
    DAO.connect();

}

public void sessionDestroyed(HttpSessionEvent sessionEvent) 
{
    System.out.println("Session destroyed");
    String user = (String) sessionEvent.getSession().getAttribute("userid" );
    if (user != null) DAO.signUserOut(user);
    DAO.disconnect();
}

现在的问题是:


  1. 我担心这种方式实际上会降级为只有每个人共享的一个连接(而不是每个用户想要的连接),只是我不时断开连接时间,如果没有用户。

  2. 如果多个用户在线并关闭会话,他们将为所有人关闭连接,直到其他人开始会话并为所有人创建新连接,对吗?我无法对此进行很好的测试,因为我正在使用3种浏览器的笔记本电脑上进行本地测试,但是即使关闭了浏览器,该会话也不会立即终止并且我不确定到底发生了什么。我所知道的是,有时我会收到一条异常消息,即连接关闭后不允许进行任何事务。


推荐答案

通常,这是使用连接池实现的。您可以将其配置为具有特定数量的可用连接,并且该池管理打开和关闭连接。您的代码将仅从池中获取可用的连接,并在完成后返回它。

Typically this is achieved using connection pool. You can configure it to have specific number of connections available and the pool manages open and closing connections. Your code will only take available connection from the pool and return it when done.

请参阅此(相当通用)维基百科文章

See this (fairly generic) Wikipedia article.

一些众所周知的池是 DBCP C3P0

Some well known pools are DBCP and C3P0.

这篇关于如何在Java Servlet应用程序上为每个用户创建一个数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆