一、 Tomcat JNDI
JNDI(java nameing and drectory interface),是一组在Java应用中访问命名和服务的API,所谓命名服务,即将对象和名称联系起来,使得可以通过名称访问并获取对象。
简单原理介绍:点击访问
tomcat已经集成该服务(内置并默认使用DBCP连接池),简单来说就是键值对的mapping,而且在tomcat服务器启动的首页configuration中就已经有完成的示例代码。要想使用tomcat的JNDI服务,只需要导入相关的jar包,建立所需的配置文件,采用JDK的命名服务API根据配置名称即可获得相应的服务。每个步骤的详细解释以及范例如下文所述。
1. jar包导入
tomcat内置了DBCP并默认使用该连接池,在tomcat的lib包中已经DBCP的两个jar包,因此不需要导入,如果使用其他连接池技术,则需要重新拷贝连接池的jar包。拷贝数据库驱动包到tomcat lib目录下,完成jar包的导入。
细节:将所需jar包直接拷贝到tomcat的lib目录中,而不是在应用中build path导入jar包。这是因为JNDI的原理类似于windows的注册表,通过配置文件(context.xml:下节详细介绍)在tomcat启动的时候就告诉tomcat在其命名服务目录下对应着配置文件中的服务名字创建服务应用。这是tomcat对外提供的一个整体服务,而不是单独对某一个应用提供的服务。
2. 配置文件:comtext.xml
在META-INF目录下建立context.xml配置文件,在文件中需要配置资源名字name和资源类型type,建立文件的目的就是告诉服务器根据服务名字创建相应的服务应用。
如下示例(DBCP),服务名称是“jdbc/mybatis-jndi”,对应的服务类型是“javax.sql.DataSource”,即通过Tomcat提供的JNDI服务,根据name=“jdbc/mybatis-jndi”可以获取到type=“javax.sql.DataSource”的服务,至于type中还需要配置什么东西,则根据实际的type类型来进行配置即可。
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<!-- maxActive: Maximum number of database connections in pool. Make sure
you configure your mysqld max_connections large enough to handle all of your
db connections. Set to -1 for no limit. -->
<!-- maxIdle: Maximum number of idle database connections to retain in pool.
Set to -1 for no limit. See also the DBCP documentation on this and the minEvictableIdleTimeMillis
configuration parameter. -->
<!-- maxWait: Maximum time to wait for a database connection to become available
in ms, in this example 10 seconds. An Exception is thrown if this timeout
is exceeded. Set to -1 to wait indefinitely. -->
<!-- username and password: MySQL username and password for database connections -->
<!-- driverClassName: Class name for the old mm.mysql JDBC driver is org.gjt.mm.mysql.Driver
- we recommend using Connector/J though. Class name for the official MySQL
Connector/J driver is com.mysql.jdbc.Driver. -->
<!-- url: The JDBC connection url for connecting to your MySQL database. -->
<Resource name="jdbc/mybatis-jndi" auth="Container" type="javax.sql.DataSource"
maxActive="100"