我使用ContextListener创建了连接池,并将此项目托管到tomcat.my配置部分,如下所示。
在tomcat confg context.xml中的我已经定义了如下资源。
<Resource name="jdbc/TEST_DS"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@server:1521/db"
username="uname"
password="pwd"
maxPoolSize="50"
removeAbandoned="true"
removeAbandonedTimeout="1000"
logAbandoned="true"
/>
现在在ContextListener中使用此资源,如下所示。
public class ConnectionListener implements ServletContextListener {
private DataSource dataSourceOracle = null;
private Connection connectionOracle = null;
private static final String ATTRIBUTE_NAME = "config";
public void contextDestroyed(ServletContextEvent sce) {
try {
if(connectionOracle!=null && !connectionOracle.isClosed() ){
this.connectionOracle.close();
this.connectionOracle = null;
}
ApplicationUtil.setServletContext(sce.getServletContext());
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void contextInitialized(ServletContextEvent event) {
ServletContext servletContext = event.getServletContext();
try {
String oracleDsName = servletContext.getInitParameter("oracle.ds.name");
Context ctx = new InitialContext();
Context envContext = (Context) ctx.lookup("java:/comp/env");
dataSourceOracle = (DataSource) envContext.lookup (oracleDsName);
connectionOracle = dataSourceOracle.getConnection();
System.out.println("testing Oracle connection >> "+connectionOracle);
ApplicationUtil.setServletContext(event.getServletContext());
} catch (SQLException e) {
e.printStackTrace();
}
catch (NamingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
servletContext.setAttribute(ATTRIBUTE_NAME, this);
}
public Connection getOracleConnection() throws SQLException, ClassNotFoundException {
return this.connectionOracle;
}
public static ConnectionListener getInstance(ServletContext servletContext) {
return (ConnectionListener) servletContext.getAttribute(ATTRIBUTE_NAME);
}
}
现在使用方法调用此连接:
public class ApplicationUtil {
private static ServletContext context;
/* Called by Listener */
public static void setServletContext(ServletContext context){
ApplicationUtil.context = context;
}
/* Use this method to access context from any location */
public static ServletContext getServletContext(){
return ApplicationUtil.context;
}
}
public class DBAccess {
ServletContext context = null;
public DBAccess(ServletContext cnt) {
context = cnt;
}
public Connection getOracleConnection() throws SQLException, ClassNotFoundException {
return ConnectionListener.getInstance(context).getOracleConnection();
}
public List getLanguageList() {
Connection cn = getOracleConnection();
...
}
}
这些都是我创建的连接池。现在的问题是当服务器关闭连接时将关闭。我需要每次重新启动tomcat以重新建立连接池。
有没有解决这个问题的永久解决方案?
任何建议都会受到欢迎。
先谢谢。
答案 0 :(得分:2)
数据库连接无法在数据库中存活。当数据库关闭时,连接丢失 不要在上下文初始化中获取并存储连接对象 每次需要时都要求池连接,并在处理完毕后将其释放。 如果有时db不是startet,则会出现必须处理的错误,但如果db重新启动,则可以在不重新启动tomat的情况下获得连接。