JNDI:java naming dictionary interface(java 命名目录接口)。 该项技术是一种java 提供的服务,是为了减少因为用户每访问一次就需要创建一次数据库额连接而增加对服务器的资源的消耗。
在这里以tomcat服务器为例子,梳理JNDI的原理。
在tomcat中配置JNDI(根据tomcat的document)分为四步。
1、在tomcat的lib文件目录下加入一个数据库的驱动 (JDBC Driver)
2、在你的web项目下的/WEB-INF/web.xml下加入一个节点:
resource-ref> <description> Resource reference to a factory for java.sql.Connection instances that may be used for talking to a particular database that is configured in the <Context> configurartion for the web application. </description> <res-ref-name> jdbc/EmployeeDB </res-ref-name> <res-type> javax.sql.DataSource </res-type> <res-auth> Container </res-auth> </resource-ref>
3、改变你的数据库连接方式:
Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); DataSource ds = (DataSource) envCtx.lookup("jdbc/EmployeeDB"); Connection conn = ds.getConnection();
4、编辑tomcat的 contex的文件:
Context ...> ... <Resource name="jdbc/EmployeeDB"//jdbc/数据库的名称 auth="Container" type="javax.sql.DataSource" username="dbusername"//用户名 password="dbpassword"//用户密码 driverClassName="org.hsql.jdbcDriver"//驱动的类名 url="jdbc:HypersonicSQL:database"//资源地址 maxActive="8"//最大可连接数 maxIdle="4"/>注意:通过JUNI的方式创建数据库的链接方式(推荐是在项目上线运行之后使用)。