这是一个非常值得问的问题,因为在互联网上几乎找不到类似的问题。
好吧,在Gwt发明之前的许多年前,我使用HttpServlet来编写Java web应用程序&我经常把Connection对象放在Servlet中。
public class JDBCServlet extends HttpServlet {
private Connection connection;
public void init(ServletConfig c) throws ServletException {
//Open the connection here
}
public void destroy() {
//Close the connection here
}
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException {
//Use the connection here
Statement stmt = connection.createStatement();
..<do JDBC work>..
}
}
但是,现在,随着Gwt&RPC调用。我使用eclipse来开发我的带有Gwt前端的Java Web应用程序。好的,在eclipse中的Server包中,我有一个名为Data.java 的类
private static ConnectionPool connectionPool;
public static void initConnectionPool() throws UnavailableException{
try {
String username="root";
String password="";
String url ="jdbc:mysql:.....";
String driver="com.mysql.jdbc.Driver";
if(connectionPool==null)
connectionPool = new ConnectionPool(url, username, password, driver, 5, 2); //initialise 5 Connections & put them into the pull, if all connections were used it will add 2 more connections to the pool.
}
catch (Exception e) {
throw new UnavailableException("Couldn't create connection pool");
}
}
public static void testDB(){
Connection myCon = null;
PreparedStatement myPreparedStmt=null;
try{
initConnectionPool();
myCon=connectionPool.getConnection();
myPreparedStmt=myCon.prepareStatement("select * from table1");
ResultSet results=myPreparedStmt.executeQuery();
//do something here
}
好吧,让我们看看这个场景,有5个不同的人生活在5个不同国家,他们都同时访问一个调用testDB()方法的网页(但第一个会比其他4个稍早打开页面)。
我测试了&发现第一个打开页面的人将在系统中创建5个连接。然后,如果第2个、第3个、第4&第5个同时访问同一页面,则系统不会创建更多的连接s(系统将首先通过initConnectionPool()方法&检查是否有任何可用的未使用连接,如果有,则它将重用它,因为该连接是由第一个用户创建的。
如果第2、3、4、5个同时打开该页面,那么他们实际上使用了5个未使用的连接中的4个,因为第1个完成了下载所有数据,所以第1个已经释放了与池的连接。
假设第二次刷新该页面,那么系统将读取initConnectionPool()方法&实际上,第二个将使用五分之一的可用未使用连接,因为每个人都已经在testDB()中下载了数据,所以他们都将连接返回到池中。如果有很多人在sme时间打开页面,那么系统会根据需要向池中添加2个或更多的Connection对象。
这是我的问题:
在GwtRPC示例中,即使我尝试放置private static Connection connection;
或public static Connection connection;
,也不会有任何区别。所以关键字private or public
在JDBC连接对象的范围内不会有任何区别?。
意思是:
-如果我们把Connection connection;
放在Data类的一个方法中,那么只有当对该方法进行页面调用时,才会打开该连接。例如,如果5个人打开该页面,那么它将创建5次连接。这是正确的吗?
-如果我们将Connection connection;
放在Data类的方法之外,那么该连接将为任何人打开。如果第一个创建了该连接(不要关闭它),那么其他人可以重用该连接,因为该连接存在于生命周期中。这是正确的吗?
但是,HttpServlet示例又如何呢。有两种解释(哪种解释是正确的?):
-每次用户加载页面时,系统都会调用public void init(ServletConfig c)
方法来创建新的连接。如果5个人同时调用同一个页面,系统将创建5个连接,该怎么办?。
-或者,连接是永久创建的,只创建了1个连接。如果5个人同时打电话,&如果第三个幸运地首先建立了连接,那么其他4个必须在队列中等待,直到第三个完成。
在GwtRPC示例中,创建了连接&从未关闭。只有关闭应用程序,它才会关闭?
但只有关闭tomcat,我们才会关闭应用程序。
如果没有人长时间使用连接,那么Mysql是否会通过某种机制使空闲连接自动关闭,或者Mysql仍然永远保持这些空闲连接的活动状态(例如,我们从未关闭tomcat&Mysql服务器多年,那么这些连接仍然活动多年?我在这一点上很困惑。
我希望有人能帮我澄清一下。
GWT RPC使用RemoteServiceServlet,它是从javax.servlet.http.HTTPServlet扩展而来的。它只是一个普通的servlet,不同之处在于您不必自己编写代码,它是生成的。