使用jndi
1.tomcat/conf/server.xml
在host标签内加上
<!-- mysql连接池配置 -->
<Context docBase="D:\apache-tomcat-5.5.25\webapps\Test" path="/test" reloadable="true">
<Resource name="jdbc/test" type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
maxIdle="2" maxWait="5000"
removeAbandoned="true" removeAbandonedTimeout="60" logAbandoned="true" username="" password="" url="jdbc:mysql://127.0.0.1:3306/abroad_test?autoReconnect=true&autoReconnectForPools=true" maxActive="100"/>
<Manager className="org.apache.catalina.session.PersistentManager" saveOnRestart="false">
<Store className="org.apache.catalina.session.FileStore" />
</Manager>
</Context>
其中1.1
removeAbandoned="true" removeAbandonedTimeout="60" logAbandoned="true"这三个参数是后来加的。
参考:http://www.exam8.com/computer/Java/zonghe/200809/658150.html这篇文章。
但是加了之后,发现会出现一些日志错误(可能是log4j定义级别为INFO的缘故)。
查资料之后发现,将conf下的logging文件里面的一些行注释掉即可。
#org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = INFO
#org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers = 3manager.org.apache.juli.FileHandler
至于注释哪些行,要根据错误来判断。注释掉后会不会引发其他问题,我没有测试。因为接下来我把数据库连接改为c3p0.
1.2
autoReconnect=true&autoReconnectForPools=true" 也是后来加的。原因是偶尔与数据库连接失败。
同时也看到网上说这些参数对mysql5以后的版本不支持。加上这些参数之后,也没有解决问题。所以要更换c3p0了。
2.applicationContext.xml
<bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/test" />
</bean>
配置完以上两步 正常启动,也可以登录连接数据库。
但是配置log4j以后发现,日志会出现以下错误:jndi name is not bound in this context。
所以加上第三步就ok了
3.项目下的WEB-INFO/web.xml 增加
<resource-ref>
<description>datasource</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
通过以上三步,运行ok。但是时间一长,还是会出现一些连接失败的问题。
难道是MYSQL 8小时问题??。还要改my.cnf???
希望有朋友告诉我怎么解决。
我已经研究了半天了,还是会出一些为问题,听说c3p0挺好,就索性改为c3p0吧.