线程池和JNDI的一些有关问题
线程池和JNDI的一些问题
今天想使用线程池,一查资料,需要使用JNDI
写个小笔记,记录一下
在web开发中使用可以配置全局和局部的
全局是指在tomcat中配置数据源,在web项目中web.xml来引用
局部是指直接在项目中的web.xml来引用
好像context.xml也可以来配置,我没有用过
另外如果使用持久层框架,配置略有不同,比如hibernate,前面一样,只是引用的时候需要在hibernate.cfg.xml中来引入。
JNDI是什么就不说了,直接配置,这里使用的是不使用持久层框架的局部配置
a). 配置应用程序WEB-INF目录下的web.xml:
<resource-ref>
<description>connection</description>
<res-ref-name>jdbc/john</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<description>connection</description>
<res-ref-name>jdbc/john</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
b).tomcat配置文件TOMCAT_HOME/conf/server.xml中context定义如下:
<Context path="/john" reloadable="false" docBase="/opt/scommnet/john" workDir="/opt/scommnet/john/work" >
<Resource name="jdbc/john"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
password="dbpwd"
maxIdle="2"
maxWait="5000"
username="dbuser"
url="jdbc:oracle:thin:@192.168.0.100:1521:cbxx"
maxActive="10"/>
</Context>
<Resource name="jdbc/john"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
password="dbpwd"
maxIdle="2"
maxWait="5000"
username="dbuser"
url="jdbc:oracle:thin:@192.168.0.100:1521:cbxx"
maxActive="10"/>
</Context>
c).调用代码
InitialContext ic = new InitialContext();
DataSource ds = (DataSource)ic.lookup("java:comp/env/jdbc/john");
try{
Connection conn = ds.getConnection();
logger.info("Connection info:"+conn.getMetaData().getDriverName());
//数据查询操作
}
catch(Exception ex){
ex.printStackTrace();
logger.error(ex.getMessage(),ex);
}
DataSource ds = (DataSource)ic.lookup("java:comp/env/jdbc/john");
try{
Connection conn = ds.getConnection();
logger.info("Connection info:"+conn.getMetaData().getDriverName());
//数据查询操作
}
catch(Exception ex){
ex.printStackTrace();
logger.error(ex.getMessage(),ex);
}